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 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 displays3and setsnto2.Python checks the condition again. It is true, so the body runs: it displays
2and setsnto1.Python checks the condition again. It is true, so the body runs: it displays
1and setsnto0.Python checks the condition again.
0 > 0is false, so the loop ends. Python runs the code after the loop, which displaysBlastoff!.
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:
The condition depends on at least one variable. Here the condition is
n > 0, and the variable isn.The variable in the condition gets its value before the loop starts. Here
n = 3comes before thewhilestatement.The body changes a variable in the condition, so that the condition can become false. Here
n = n - 1makesnsmaller each time, untiln > 0is false.The body is the indented block after the colon. Only the indented lines repeat.
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:
result = 1sets up the answer before the loop starts.The condition is
n > 1. The loop repeats whilenis more than 1.The body multiplies
resultbyn, then subtracts 1 fromn.When
nis 1, the condition is false, the loop ends, and the function returnsresult.
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,
resultis1andnis3.First iteration:
3 > 1is true, soresultbecomes3andnbecomes2.Second iteration:
2 > 1is true, soresultbecomes6andnbecomes1.The check
1 > 1is false, so the loop ends, and the function returns6.
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:
rowis1. The outer conditionrow <= 3is true, so the outer body runs. It setscolto1, and the inner loop runs 4 times, withcolequal to 1, 2, 3 and 4. It displays1 2 3 4on one line, becauseend=' 'puts a space after each number instead of a newline. Whencolis5, the inner loop ends.print()ends the line, androwbecomes2.rowis2. The outer body setscolback to1, and the inner loop displays2 4 6 8.rowis3. The inner loop displays3 6 9 12.rowis4, 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:
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.Change the variable of the inner loop (
col = col + 1) in the inner body.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.
startgets its first value before the outer loop, andstart = start + 1is the last line of the outer body.The inner loop follows the sequence of one start number. Its variables
nandstepsget 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,
stepsis the number of steps of this start number. Theifstatement 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.
Diving deeper: a for loop written as a while loop
Any for loop over a range can be written as a while loop. This for loop:
for i in range(3):
print(i)
displays the same values as this while loop:
i = 0
while i < 3:
print(i)
i = i + 1
The while version needs three extra pieces: set i to 0 before the loop, check i < 3,
and add 1 to i in the body. The for loop does all three for you. For when to use each
kind of loop, see When to use a while loop above.
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')
Answer
2
1
Done
The loop runs twice: it displays 2, then 1. When n is 0, the condition is false, the loop ends, and Done is displayed.
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)
Answer
4 times. n is 10, 7, 4, then 1 at the four checks where the condition is true. After the fourth run, n is -2, the condition is false, and the loop ends. The code displays 4.
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))
Answer
6
The answer is 6, not 24. The body decreases n before it multiplies, so result is multiplied by 3, then by 2, then by 1: 1 * 3 * 2 * 1 = 6. The multiplication by 4 never happens. The order of the lines in the body matters.
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!')
Answer
The body never changes n, so the condition n > 0 stays true forever. Calling countdown(3) displays 3 forever: an infinite loop. The fix is to decrease n in the body:
def countdown(n):
while n > 0:
print(n)
n = n - 1
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
Answer
1
2 4
3 6 9
The inner condition is j <= i, so the inner loop runs i times: once when i is 1, two times when i
is 2, and three times when i is 3. Each line displays i times 1, 2, … up to i. (Each line ends with
a space, which you cannot see.)
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')
Answer
1 1
1 2
Done
The outer loop runs 3 times, but the inner body runs only 2 times in all. j = 1 is before the outer loop,
so j is set only once. After the first iteration of the outer loop, j is 3, and the inner condition
j <= 2 stays false. To display the pairs for each i, move j = 1 into the outer body, right before the
inner loop.
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.
Answer
def add_numbers():
total = 0
text = input('number (or done): ')
while text != 'done':
total = total + int(text)
text = input('number (or done): ')
return total
The question appears twice: once before the loop, and once at the end of the body. The loop stops when the user types done. Each reply that is not done is changed to a whole number with int and added to total.
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):
...
Answer
def count_digits(n):
count = 0
while n > 0:
count = count + 1
n = n // 10
return count
Each iteration removes the last digit (n // 10) and adds 1 to the count. The loop ends when n is 0, so the count is the number of digits.
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):
...
Answer
def is_prime(n):
if n < 2:
return False
divisor = 2
while divisor < n:
if n % divisor == 0:
return False
divisor = divisor + 1
return True
The loop tries each possible divisor from 2 up to n - 1. If one divides n evenly, n is not prime. If none does, n is prime. For n less than 2, the function returns False before the loop.
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):
...
Answer
def power(base, exponent):
result = 1
count = 0
while count < exponent:
result = result * base
count = count + 1
return result
The body multiplies result by base once per iteration, and the loop runs exponent times. For an exponent of 0, the condition is false at the first check, so the loop never runs, and the function returns 1.
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):
...
Answer
def print_number_triangle(n):
line = 1
while line <= n:
number = 1
while number <= line:
print(number, end=' ')
number = number + 1
print()
line = line + 1
The outer loop goes through the lines. For each line, the inner loop displays the numbers from 1 to the
number of the line. number = 1 is in the outer body, so that each line starts again at 1. print() ends the
line after the inner loop.
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):
...
Answer
def digital_root(n):
while n >= 10:
total = 0
while n > 0:
total = total + n % 10
n = n // 10
n = total
return n
The outer condition n >= 10 is true while n has more than one digit. In the outer body, the inner loop
adds the last digit (n % 10) to total and removes it (n // 10), until no digits are left. Then n
gets the sum of the digits, and the outer loop checks it again. total = 0 is in the outer body, so that
each sum starts again at 0. For a number with one digit, the outer body never runs, and the function returns
the number.
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):
...
Answer
def first_primes(count):
primes = []
n = 2
while len(primes) < count:
divisor = 2
is_prime = True
while divisor < n:
if n % divisor == 0:
is_prime = False
divisor = divisor + 1
if is_prime:
primes.append(n)
n = n + 1
return primes
The outer loop runs until the list has count numbers: no one knows before the loop how many numbers it must
try. For each number n, the inner loop tries each divisor from 2 to n - 1. divisor = 2 and
is_prime = True are in the outer body, so that each number is checked from the start. If a divisor divides
n evenly, n is not prime. After the inner loop, a prime number is added to the list.
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