while loops
Write and trace a while loop, with a counter or a sentinel, and say how many times its body runs.
It opens on
In this program n starts at 1 and is tripled while it is under 100. When the loop stops, will n be under 100, exactly 100, or over 100?
Why it matters
Every program that repeats until something happens (a game until the player quits, a download until the last byte, a search until the item is found) is a while loop, and most loop bugs are a wrong condition or a missing update.
Good to know first
- if, elif and else: a block runs only when its condition is True
- Booleans and comparisons: n < 100 evaluates to True or False
- Variables and assignment: n = n * 3 reads the old n, then binds n to the new value
Step by step
Test, run, test again
Trace a counter-controlled while loop and give the values its variables have when it stops.
Before the loop n is 1 and count is 0; the first test asks whether 1 < 100, which is True, so line 4 makes n 3 and line 5 makes count 1.
A common mix-up
The loop stops as soon as n reaches 100.
In fact: The condition is tested only at the top, so the last run takes n from 81 to 243 and the loop stops after it.
Stop on a sentinel
Write and trace a loop that reads values until a sentinel value, and keep a running total.
Say the user types 4, 7, 2 and then 0. The first input gives x = 4; 4 != 0 is True, so total becomes 4 and the next input gives x = 7.
A common mix-up
The sentinel is processed like the other values.
In fact: It is tested before the block, so it ends the loop without being added; a sentinel of -1 would otherwise lower the total.
Count the runs, find the bug
Count how many times a while loop's block runs from its start, condition and update, and fix a loop that never ends or runs once too often.
The first loop prints 0, 1, 2, 3, 4. With i starting at 0 and going up by 1 while i < 5, it runs 5 times, one for each value from 0 to 4.
A common mix-up
i <= 5 and i < 5 run the same number of times.
In fact: <= lets i = 5 through, one more run.
Try it
For n = 2 and count = 0, with while n < 50: n = n * 2 and count = count + 1, what does print(count, n) show?Answer
5 64
Hint: n goes 4, 8, 16, 32, 64
The user types 10, 20, 30, 0. What does the program print, and how many times did the block run?Answer
Total 60; 3 times
Hint: One run per number before the 0
How many times does this block run: i = 2, while i < 11: i = i + 3?Answer
3 times
Hint: i is 2, 5, 8, then 11 fails
Now n is 27. What are n and count after the next run of the block?Answer
n is 81 and count is 4, because 27 < 100 is True.
What is total after x = 2 is used, and what happens when x is 0?Answer
Total is 13; 0 != 0 is False, so the loop ends and the program prints total 13.
