CMPT 120 Lab 4

This site applies only to CMPT 120 D1 (Burnaby) in Summer 2011. See the other instructors' pages for other sections.

  1. We want to write a program that counts for the user. It should ask them where to start, end, and what it should count by:
    Start at: 3
    End at: 10
    Count by: 2
    3 5 7 9
    Start at: 100
    End at: 120
    Count by: 5
    100 105 110 115 120

    Assume that the “count by” value is 1 or larger and thay the end value is greater than the start value. You can keep print from ending the line by ending the statement with a comma. For example, this program will print the numbers 1 to 9, counting by 2, on a single line:

    for i in range(1, 10, 2):
        print i,

    1. Write this program using a for loop.
    2. Write this program using a while loop.
  2. This question involves finding spaces in a string. Remember that you can extract a single character from a string by indexing: s[i] for a string s and integer i. The first character in a string is s[0].

    Hints: Use a for loop for one part, and a while loop for the other. The range range(len(s)) will give the positions of the characters in a string s; you can use this in a for loop to iterate over each character in a string.

    1. Write a program that reports every occurrence of a space:
      Enter a string: This is the user's input
      There's a space in position 4.
      There's a space in position 7.
      There's a space in position 11.
      There's a space in position 18.
    2. Write a program that reports the position of the first space:
      Enter a string: This is the user's input
      The first space is in position 4.
  3. In a Python program, create a function named triple that takes one number as its argument. It should return three times that number.

    In the main part of the program (below the function definition), insert this code:

    print "This should be nine:", triple(3)
    print "This should be negative 120:", triple(-40)

    When this program is run, the output must be exactly this:

    This should be nine: 9
    This should be negative 120: -120