3c. Additions: More About for Loops#

Additions to Chapter 3: Functions: how a for loop runs, step by step, what happens to the loop variable, how to add up values in a loop, and a rule that you must never break: do not change the iterable of a loop in the body of the loop. The last section shows how to watch a for loop run in the Thonny debugger. Read this page after the chapter and after “3b. Additions: The Three Forms of range”. The practice questions at the end have answers: try each question first, then open its Answer.

Run this page on Colab

Run the setup cell below first. It downloads thinkpython.py, which lets this page show the errors of some examples without stopping the page.

from os.path import basename, exists

def download(url):
    filename = basename(url)
    if not exists(filename):
        from urllib.request import urlretrieve

        local, _ = urlretrieve(url, filename)
        print("Downloaded " + str(local))
    return filename

download('https://github.com/AllenDowney/ThinkPython/raw/v3/thinkpython.py');

import thinkpython

How a for loop runs#

The general form of a for loop is:

for VARIABLE in ITERABLE:
    BODY
  • ITERABLE is a value that gives other values, one at a time. In Chapter 3, the iterable is always a range. Later chapters loop over other iterables: the characters of a string and the lines of a file (Chapter 7), and the items of a list (Chapter 9).

  • VARIABLE is the loop variable. Each time the loop runs, Python assigns the next value of the iterable to it.

  • BODY is the indented block after the colon. One run of the body is one iteration.

Python runs a for loop in these steps:

  1. Get the next value from the iterable. If there are no more values, the loop ends: go on with the code after the loop.

  2. Assign the value to the loop variable.

  3. Run the body.

  4. Go back to step 1.

for i in range(3):
    print('Iteration', i)
print('After the loop')
Iteration 0
Iteration 1
Iteration 2
After the loop

Step by step: range(3) gives the values 0, 1 and 2. Python assigns 0 to i and runs the body, which displays Iteration 0. Then it assigns 1 to i and runs the body, then 2. There are no more values, so the loop ends, and Python runs the line after the loop. That line is not indented, so it is not part of the body: it runs once.

The loop variable#

After the loop, the loop variable keeps its last value.

for i in range(1, 4):
    print(i)
print('After the loop, i is', i)
1
2
3
After the loop, i is 3

A loop over an empty range does not run its body. range(0) gives no values, so the body runs zero times, and the loop variable gets no value:

for i in range(0):
    print('This line never runs')
print('Done')
Done

Each function has its own loop variable. A loop variable is a variable like any other. When a loop is in a function, its variable is local to the function (“Variables and parameters are local” in Chapter 3). In this program, print_row and print_box each have a variable i. They are two different variables, so the loop in print_row does not change the i of print_box:

def print_row(width):
    line = ''
    for i in range(width):
        line = line + '*'
    print(line)

def print_box(height, width):
    for i in range(height):
        print_row(width)

print_box(3, 5)
*****
*****
*****

print_row makes a string of stars: it starts with the empty string '', and the body adds one '*' in each iteration. print_box calls print_row once in each iteration of its loop, so it displays 3 rows. The last section of this page shows how to watch this program run in Thonny.

Adding up values in a loop#

To add up values, make a variable for the total before the loop, with the value 0. In the body, add the value of each iteration to it. After the loop, the variable has the sum:

total = 0
for number in range(1, 6):
    total = total + number
print('The sum of 1 to 5 is', total)
The sum of 1 to 5 is 15

total = total + number means: get the value of total, add number, and assign the result to total. The values of total after each iteration are 1, 3, 6, 10 and 15.

The line total = 0 must be before the loop. In the body, it would set the total back to 0 in each iteration. Chapter 7 says more about updating a variable in a loop.

Never change the iterable in the body of a loop#

The rule: in the body of a for loop, do not change the iterable that the loop goes through. Code that does this is very bad code. It can make the loop run more or fewer times than it seems to, give a wrong result without an error message, or never end, and a person who reads it cannot see what it does. Never write such code.

In Chapter 3, the iterable is always a range, and a program cannot change a range: a range is immutable. The book teaches iterables that a program can change (they are mutable) later: lists in Chapter 9, and dictionaries in Chapter 10. “9b. Additions: Iterables, and Changing a List in a Loop” shows what goes wrong when a loop changes its list, and “10b. Additions: More About Dictionaries” what goes wrong when a loop changes its dictionary.

Do not assign to the loop variable#

The same rule is true for the loop variable. At the start of each iteration, Python assigns the next value of the range to the loop variable. A value that the body assigns to the loop variable is lost at the next iteration:

for i in range(4):
    i = i * 10
    print(i)
0
10
20
30

The loop still runs 4 times, with i equal to 0, 1, 2 and 3 at the start of the iterations. A reader can think that the change to i changes the loop, and it does not. If you need a changed version of a value, make a new variable in the body, as line and total above: ten_times = i * 10.

Watch a for loop in Thonny#

Thonny is a program for writing and running Python on your own computer. Its debugger runs a program one step at a time and shows the value of each variable. To install Thonny, and to learn the two parts of its window, read Another Note From Prof. Rosenthal: Using Thonny.

  1. Start Thonny. Copy the print_row and print_box program from the section “The loop variable” into the editor (the top part of the window), and save it as box.py.

  2. Click View, then Variables, to see the values of the variables while the program runs.

  3. Start the debugger: click the Debug button (the picture of a bug), or press Ctrl+F5. Thonny puts a box around the part of the code that runs next.

  4. Press Step over (F6) many times. Each time, Thonny runs the part in the box, and moves the box to the next part. Look at the box when the program is in a loop: it goes from the body back to the for line, and the loop variable gets its next value.

  5. When the box is on the call print_row(width), press Step into (F7) until Thonny opens a small window for the call of print_row (Step into first goes into the parts of the line, then into the function). It shows the code of the function and its local variables: width, i and line. This is the frame of the call, as in the stack diagrams of Chapter 3. Press Step over and watch line get one more star in each iteration. (If Thonny shows the call in the editor, not in a small window, click Tools, Options, Run & Debug, and select “Show function calls (frames) in separate windows”.)

  6. Press Step out to run the rest of the call. The window of the call closes, and Thonny goes back to the loop of print_box. Its i did not change: each function has its own i.

  7. To stop the program before it ends, click the red Stop button (Ctrl+F2).

Then try the example “Do not assign to the loop variable” in Thonny. With Step over, watch i in the Variables view: the body changes it to 0, 10, 20 and 30, but at the start of each iteration the loop gives it the next value of the range, 1, 2 and 3.

On a Mac, the keys F5 to F8 can control the screen or the sound. Hold down the fn key, or click the buttons of Thonny instead. “11c. Additions: The Thonny Debugger” tells more about the debugger.

Practice questions#

Question 1 (very easy): what is displayed?#

Predict what this code displays. Then run the cell to check (on the website, click Show code cell output).

for i in range(3):
    print('hi', i)

Hide code cell output

hi 0
hi 1
hi 2

Question 2 (easy): what is displayed?#

Predict what this code displays. Then run the cell to check (on the website, click Show code cell output).

for i in range(2):
    print('A')
    print('B')
print('C')

Hide code cell output

A
B
A
B
C

Question 3 (easy): what is displayed?#

Predict what this code displays. Then run the cell to check (on the website, click Show code cell output).

total = 0
for number in range(2, 11, 2):
    total = total + number
print(total)

Hide code cell output

30

Question 4 (medium): what is displayed?#

Predict what this code displays. Then run the cell to check (on the website, click Show code cell output).

total = 0
for i in range(1, 4):
    total = total + i
print(i, total)

Hide code cell output

3 6

Question 5 (medium): what is displayed?#

Predict what this code displays. Then run the cell to check (on the website, click Show code cell output).

def show(n):
    for i in range(n):
        print('show', i)

for i in range(2):
    show(3)
    print('main', i)

Hide code cell output

show 0
show 1
show 2
main 0
show 0
show 1
show 2
main 1

Question 6 (medium): what is wrong?#

A student wants to display the numbers 0, 10, 20 and 30, and writes this code. It displays the right numbers. Why is it bad code anyway? Write a better version.

for i in range(4):
    i = i * 10
    print(i)

Question 7 (hard): write a function#

Write a function called print_sum that takes a whole number n, 0 or more, and displays the sum 1 + 2 + … + n. Use a for loop.

For example, print_sum(4) displays 10, print_sum(1) displays 1, and print_sum(0) displays 0.

Start from this header (replace ... with the body):

def print_sum(n):
    ...

Question 8 (hard): write a function#

Write a function called print_triangle that takes a whole number height and displays a triangle of stars: the first row has 1 star, the second row 2 stars, and so on, up to height stars. Use a for loop, and call the function print_row from the section “The loop variable” in it.

For example, print_triangle(3) displays:

*
**
***

Start from this header (replace ... with the body):

def print_triangle(height):
    ...

Credits#

Additions by Prof. Y. Rosenthal, for Think Python: 3rd Edition by Allen B. Downey. Text license: Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International