CPSC120A
Fundamentals of Computer Science I

Activity 7

Exploring how to control for loops with the range function.

Range

You can use the simple version of the range(n) function to write any loop in Python. But there are some programs that can be written more succinctly by taking advantage of the range function's optional arguments. In this activity you will explore what those parameters are and how they can be used.

Details

  1. Fill in the following table. For each row of the table, write a Python program that evaluates the expression on the left. Put the result in the column on the right.

    ExecuteResult
    for i in range(6):
        print(i)
    for i in range(1, 6):
        print(i, end=' ')
    for i in range(1, 6, 2):
        print(i, end=', ')
  2. Given the above results, explain how the range function works. Include an explanation of the function's arguments.

  3. What does the end=' ' argument do for print statements?

  4. Consider the following output of a Python program. Write the for loop statement that will produce the specified output.

    ResultsFor Loop
    1 2 3 4 5 6
    
    3 6 9 12 15 18 21
    
    0 5 10 15 20 25 30 35 40
    
    0 -1 -2 -3 -4 -5
    
    5 4 3 2 1 0
  5. Write a for loop that prints the even numbers between 100 and 200, inclusive.