11b. Additions: While Loops#

Additions to Chapter 11: Tuples: the while loop, a loop that repeats while a condition is true. The book does not teach the while statement: every loop in the book is a for loop. A while loop is the right tool when the number of repetitions depends on a condition, not on a fixed sequence of values. The page also shows nested while loops: a while loop in the body of another. The examples use lists (Chapter 9) and tuple assignment (Chapter 11). Read this page after the chapter. 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, the helper module the chapters use.

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');
download('https://github.com/AllenDowney/ThinkPython/raw/v3/diagram.py');

import thinkpython

What is a while loop?#

A while statement repeats a block of code while a condition is true. Its general form is:

while CONDITION:
    BODY

CONDITION is an expression that is True or False, like the condition of an if statement. BODY is the indented block after the colon. Python checks the condition before each run of the body. If the condition is true, the body runs. If the condition is false, the loop ends, and Python runs the code after the loop.

A while statement looks like an if statement, but it behaves differently after the body runs. After the body of an if statement runs, Python moves on to the code after the if. After the body of a while statement runs, Python checks the condition again. If it is still true, the body runs again. The loop repeats while the condition stays true.

Here is a countdown:

n = 3
while n > 0:
    print(n)
    n = n - 1
print('Blastoff!')
3
2
1
Blastoff!

Here is what happens, step by step. Before the loop, n is 3.

  • Python checks the condition n > 0. It is true, so the body runs: it displays 3 and sets n to 2.

  • Python checks the condition again. It is true, so the body runs: it displays 2 and sets n to 1.

  • Python checks the condition again. It is true, so the body runs: it displays 1 and sets n to 0.

  • Python checks the condition again. 0 > 0 is false, so the loop ends. Python runs the code after the loop, which displays Blastoff!.

Each run of the body is one iteration. We say that the loop iterates: this loop iterates 3 times. To follow a loop, write the values of the variables on paper and update them line by line, as above.

When to use a while loop#

Use a while loop when you cannot tell, at the time you write the code, how many times the loop will run. Use a for loop when you can tell: when the values are ready before the loop starts.

This for loop runs 5 times. The list is ready before the loop starts, so the count is known when you write the code:

for n in [3, 1, 4, 1, 5]:
    print(n * 2)
6
2
8
2
10

This while loop doubles n until it passes 100. How many times does it run? You cannot tell by reading the code. You have to run it. The loop stops when the condition turns false, not after a set count:

n = 1
while n <= 100:
    n = n * 2
print(n)
128

The rule is about what you know when you write the code. If the values are ready first, use a for loop. If the loop must keep going until something happens, use a while loop. The guessing game later on this page is an example: no one knows how many guesses it will take.

The parts of a while loop#

When you write a while loop, keep these rules in mind:

  1. The condition depends on at least one variable. Here the condition is n > 0, and the variable is n.

  2. The variable in the condition gets its value before the loop starts. Here n = 3 comes before the while statement.

  3. The body changes a variable in the condition, so that the condition can become false. Here n = n - 1 makes n smaller each time, until n > 0 is false.

  4. The body is the indented block after the colon. Only the indented lines repeat.

  5. The condition is checked before each iteration. If it is false at the first check, the body never runs:

n = 0
while n > 0:
    print(n)
    n = n - 1
print('Done')
Done

The condition 0 > 0 is false before the first check, so the body never runs, and only Done is displayed.

Example: factorial#

In math, the factorial of a whole number is the product of that number and all the positive whole numbers below it. The factorial of 5 is 5 * 4 * 3 * 2 * 1, which is 120. Mathematicians write 5! for the factorial of 5. The factorial of 0 and the factorial of 1 are both defined to be 1.

Python’s math module has a function that computes factorials:

import math
print(math.factorial(0))
print(math.factorial(1))
print(math.factorial(5))
1
1
120

Here is the same function written with a while loop. It takes a whole number n, 0 or more:

  1. result = 1 sets up the answer before the loop starts.

  2. The condition is n > 1. The loop repeats while n is more than 1.

  3. The body multiplies result by n, then subtracts 1 from n.

  4. When n is 1, the condition is false, the loop ends, and the function returns result.

def factorial(n):
    result = 1
    while n > 1:
        result = result * n
        n = n - 1
    return result

print(factorial(0))
print(factorial(1))
print(factorial(3))
print(factorial(5))
1
1
6
120

For factorial(3), the values change like this:

  • At the start, result is 1 and n is 3.

  • First iteration: 3 > 1 is true, so result becomes 3 and n becomes 2.

  • Second iteration: 2 > 1 is true, so result becomes 6 and n becomes 1.

  • The check 1 > 1 is false, so the loop ends, and the function returns 6.

For factorial(0) and factorial(1), the condition is false at the first check, so the body never runs, and the function returns 1, which is the correct answer.

Example: Fibonacci numbers#

The Fibonacci numbers are the sequence 0, 1, 1, 2, 3, 5, 8, 13, … The first two numbers are 0 and 1. Every other number is the sum of the two numbers before it.

This function returns the first n Fibonacci numbers as a list. It uses tuple assignment (Chapter 11): a, b = b, a + b gives a the old value of b, and b the sum of the old values, because the right side is evaluated before any assignment happens. It also uses append (Chapter 9) to add each number to the list.

def fibonacci(n):
    result = []
    a, b = 0, 1
    while len(result) < n:
        result.append(a)
        a, b = b, a + b
    return result

print(fibonacci(0))
print(fibonacci(1))
print(fibonacci(4))
print(fibonacci(8))
[]
[0]
[0, 1, 1, 2]
[0, 1, 1, 2, 3, 5, 8, 13]

The condition is len(result) < n: the loop repeats until the list holds n numbers. Each iteration appends the current value of a, then moves a and b one step forward in the sequence. For fibonacci(0), the condition is false at the first check, so the function returns an empty list.

Getting input from the user#

Chapter 5 teaches the input function. It shows a prompt, waits for the user to type a reply, and returns the reply. The reply is always a string, even when the user types a number. Use int to change it to a whole number before you compare it with numbers.

This matters because strings and numbers compare by different rules. Chapter 8 teaches that strings compare letter by letter, so '29' < '3' is True: '2' comes before '3'. The numbers compare the other way: 29 < 3 is False.

name = input('What is your name? ')
print('Hello,', name)
What is your name? mary smith
Hello, mary smith
print('29' < '3')
print(int('29') < int('3'))
True
False

The next program is a guessing game. It picks a whole number, asks the user to guess it, and keeps asking until the guess is right. It counts the guesses. random.randint(low, high) picks a whole number from low to high. The number is different each time the program runs.

No one knows how many guesses it will take, so this program needs a while loop. A for loop cannot do it: there is no list of guesses ready before the loop starts.

The cell below defines the function guessing_game. The cell displays nothing: it only defines the function.

import random

def guessing_game(low, high):
    num = random.randint(low, high)
    num_guesses = 1
    guess = int(input('guess: '))
    while guess != num:
        if guess < num:
            guess = int(input('higher, guess again: '))
        else:
            guess = int(input('lower, guess again: '))
        num_guesses = num_guesses + 1
    return num_guesses

To play the game, call the function. Do this on Colab, where you can type the replies: run the cell above, then type this call in a new cell and run it.

guessing_game(1, 100)

Here is one run of the program. The program picked 42.

guess: 50
lower, guess again: 25
higher, guess again: 37
higher, guess again: 42
4

The next program asks the user what to do, and keeps going until the user chooses to quit. The user indicates when they are done. This is the second reason a program needs a while loop: the number of rounds depends on the user. It uses guessing_game from the cell above.

The question appears twice: once before the loop, and once at the end of the body. The first question starts the loop. The question at the end lets the user stop it. If the second question is missing, the loop never ends.

def play_guessing_games():
    print('1. play guessing game')
    print('2. quit')
    choice = int(input('choice: '))
    while choice != 2:
        lowest = int(input('lowest number: '))
        highest = int(input('highest number: '))
        num_guesses = guessing_game(lowest, highest)
        print('You guessed the number in', num_guesses, 'guesses.')
        print('1. play guessing game')
        print('2. quit')
        choice = int(input('choice: '))

To play, type this call in a new cell on Colab and run it:

play_guessing_games()

Here is one run. The user plays once, then quits. The program picked 3.

1. play guessing game
2. quit
choice: 1
lowest number: 1
highest number: 10
guess: 5
lower, guess again: 2
higher, guess again: 3
You guessed the number in 3 guesses.
1. play guessing game
2. quit
choice: 2

Nested while loops#

A while loop can be in the body of another while loop. These are nested loops: the outer loop and the inner loop. In each iteration of the outer loop, the inner loop runs all of its iterations. Nested for loops work in the same way (“9c. Additions: Nested Loops”).

This code displays a table of products. The outer loop goes through the rows, and the inner loop goes through the columns of one row:

row = 1
while row <= 3:
    col = 1
    while col <= 4:
        print(row * col, end=' ')
        col = col + 1
    print()
    row = row + 1
1 2 3 4 
2 4 6 8 
3 6 9 12 

Step by step:

  • row is 1. The outer condition row <= 3 is true, so the outer body runs. It sets col to 1, and the inner loop runs 4 times, with col equal to 1, 2, 3 and 4. It displays 1 2 3 4 on one line, because end=' ' puts a space after each number instead of a newline. When col is 5, the inner loop ends. print() ends the line, and row becomes 2.

  • row is 2. The outer body sets col back to 1, and the inner loop displays 2 4 6 8.

  • row is 3. The inner loop displays 3 6 9 12.

  • row is 4, the outer condition is false, and the outer loop ends.

The inner body ran 3 × 4 = 12 times in all.

A nested while loop needs the rules of “The parts of a while loop” for each loop:

  1. Set the variable of the inner loop (col = 1) in the body of the outer loop, right before the inner loop. Then it starts again at its first value in each iteration of the outer loop.

  2. Change the variable of the inner loop (col = col + 1) in the inner body.

  3. Change the variable of the outer loop (row = row + 1) in the outer body, after the inner loop: it is indented as the outer body, not as the inner body.

The most common mistake breaks rule 1: it sets the inner variable once, before the outer loop. Here col = 1 is before the outer loop:

row = 1
col = 1
while row <= 3:
    while col <= 4:
        print(row * col, end=' ')
        col = col + 1
    print()
    row = row + 1
1 2 3 4 

Only the first row is displayed. After the first iteration of the outer loop, col is 5. Nothing sets it back to 1, so in the next iterations the inner condition col <= 4 is false at the first check, and the inner body never runs. The outer loop still runs 3 times: the two other iterations display only empty lines.

Example: the longest Collatz sequence#

The next example needs while loops, because no one knows the number of iterations before the loop runs.

A Collatz sequence starts with a whole number n, 1 or more. If n is even, the next number is n // 2. If n is odd, the next number is 3 * n + 1. The sequence ends when it gets to 1. For example, the sequence of 6 is 6, 3, 10, 5, 16, 8, 4, 2, 1: it takes 8 steps to get to 1. Mathematicians think that every start number gets to 1, but no one has proved it.

This function finds the start number, from 1 to limit, whose sequence takes the most steps. It returns a tuple: the start number and its number of steps.

def longest_collatz(limit):
    best_start = 1
    best_steps = 0
    start = 1
    while start <= limit:          # outer loop: each start number
        n = start
        steps = 0
        while n != 1:              # inner loop: the sequence of one start number
            if n % 2 == 0:
                n = n // 2
            else:
                n = 3 * n + 1
            steps = steps + 1
        if steps > best_steps:
            best_start = start
            best_steps = steps
        start = start + 1
    return best_start, best_steps
longest_collatz(10)
(9, 19)

From 1 to 10, the sequence of 9 takes the most steps: 19. The function follows the rules of nested loops:

  • The outer loop goes through the start numbers. start gets its first value before the outer loop, and start = start + 1 is the last line of the outer body.

  • The inner loop follows the sequence of one start number. Its variables n and steps get their first values in the outer body, right before the inner loop, so that each sequence starts again from its own start number with 0 steps.

  • After the inner loop, steps is the number of steps of this start number. The if statement keeps the best one so far.

The inner loop must be a while loop: the number of steps is different for each start number, and it is not known before the loop runs. The outer loop could be a for loop (for start in range(1, limit + 1):).

start, steps = longest_collatz(1000)
print('From 1 to 1000, the longest sequence starts at', start, 'and takes', steps, 'steps.')
From 1 to 1000, the longest sequence starts at 871 and takes 178 steps.

To watch nested loops run one step at a time, use the Thonny debugger (“11c. Additions: The Thonny Debugger”).

A loop that never ends#

If the body never makes the condition false, the loop never ends. It is called an infinite loop. Here is the factorial function with the update line left out:

def factorial(n):
    result = 1
    while n > 1:
        result = result * n
    return result

n never changes, so n > 1 stays true forever, and the loop repeats forever. The code above is text, not a code cell, so it cannot run. If you run an infinite loop in Colab, stop it with Runtime, then Interrupt execution.

Three mistakes cause most infinite loops: the body does not change a variable in the condition, the body changes it in the wrong direction (for example, n = n + 1 in a loop that needs n to get smaller), or the condition itself is wrong (for example, n < 1 instead of n > 1). Question 4 asks you to find such a mistake.

Practice questions#

Question 1 (easy): what is displayed?#

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

n = 2
while n > 0:
    print(n)
    n = n - 1
print('Done')

Hide code cell output

2
1
Done

Question 2 (easy): how many times?#

How many times does the body of this loop run?

count = 0
n = 10
while n > 0:
    count = count + 1
    n = n - 3
print(count)

Question 3 (medium): what is displayed?#

This is the factorial function from the page, but the two lines of the body are in the opposite order: n is decreased before result is multiplied. Predict what this code displays. Then run the cell to check (on the website, click Show code cell output).

def factorial(n):
    result = 1
    while n > 1:
        n = n - 1
        result = result * n
    return result

print(factorial(4))

Hide code cell output

6

Question 4 (medium): find the bug#

This function is supposed to count down from n and display Blastoff!, but it never finishes. What is wrong, and how do you fix it?

def countdown(n):
    while n > 0:
        print(n)
    print('Blastoff!')

Question 4b (medium): what is displayed?#

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

i = 1
while i <= 3:
    j = 1
    while j <= i:
        print(i * j, end=' ')
        j = j + 1
    print()
    i = i + 1

Hide code cell output

1 
2 4 
3 6 9 

Question 4c (medium): what is displayed?#

Predict what this code displays. How many times does the outer loop run, and how many times does the inner body run? Then run the cell to check (on the website, click Show code cell output).

i = 1
j = 1
while i <= 3:
    while j <= 2:
        print(i, j)
        j = j + 1
    i = i + 1
print('Done')

Hide code cell output

1 1
1 2
Done

Question 5 (medium): write a function#

Write a function called add_numbers that keeps asking the user for whole numbers until the user types done, and returns the total of the numbers typed.

The function takes no arguments. It asks with the prompt 'number (or done): '. If the user types done at the first question, the function returns 0.

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

def add_numbers():
    ...

Example 1: if the user types 5, then 3, then done, the function returns 8.

Example 2: if the user types done at once, the function returns 0.

Try the function on Colab, where you can type the replies.

Question 6 (hard): write a function#

Write a function called count_digits that takes a positive whole number and returns how many digits it has. Use a while loop.

For example, count_digits(7) returns 1, count_digits(42) returns 2, and count_digits(1000) returns 4.

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

def count_digits(n):
    ...

Question 7 (hard): write a function#

Write a function called is_prime that takes a whole number and returns True if the number is prime and False if it is not. A prime number is a whole number, 2 or more, that is divisible only by 1 and itself. The number 1 is not prime. Use a while loop.

For example, is_prime(2) returns True, is_prime(7) returns True, is_prime(9) returns False, and is_prime(1) returns False.

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

def is_prime(n):
    ...

Question 8 (hard): write a function#

Write a function called power that takes a base and a non-negative whole-number exponent and returns the base raised to the exponent. Use a while loop. Do not use the ** operator.

For example, power(2, 0) returns 1, power(2, 3) returns 8, and power(5, 2) returns 25.

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

def power(base, exponent):
    ...

Question 9 (hard): write a function#

Write a function called print_number_triangle that takes a whole number n, 1 or more, and displays n lines. Line 1 has the number 1, line 2 has the numbers 1 2, and so on: line n has the numbers 1 to n. Put a space after each number. Use nested while loops.

For example, print_number_triangle(4) displays:

1
1 2
1 2 3
1 2 3 4

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

def print_number_triangle(n):
    ...

Question 10 (hard): write a function#

The digital root of a whole number is the result of this procedure: add up the digits of the number, then add up the digits of the result, and so on, until the result has only one digit. For example, for 9875: 9 + 8 + 7 + 5 = 29, then 2 + 9 = 11, then 1 + 1 = 2. The digital root of 9875 is 2.

Write a function called digital_root that takes a whole number, 0 or more, and returns its digital root. Use nested while loops: the inner loop adds up the digits of a number (as count_digits in Question 6 counts them), and the outer loop repeats while the number has more than one digit.

For example, digital_root(9875) returns 2, digital_root(38) returns 2 (3 + 8 = 11, 1 + 1 = 2), and digital_root(7) returns 7.

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

def digital_root(n):
    ...

Question 11 (hard): write a function#

Write a function called first_primes that takes a whole number count, 0 or more, and returns a list of the first count prime numbers. Use nested while loops: the outer loop tries the numbers 2, 3, 4, … until the list has count numbers, and the inner loop tries the divisors of one number, as is_prime in Question 7 does. Do not call another function.

For example, first_primes(5) returns [2, 3, 5, 7, 11], and first_primes(0) returns [].

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

def first_primes(count):
    ...

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