Sub topic 3
Changing state so the loop can end
This chapter assumes you can assign variables, write comparisons and boolean expressions, use if with indentation, and call print and input. You should also know the basic shape of a while loop: a condition, then an indented body that repeats while the condition is true.
Why a loop needs changing state
Python checks the condition before every pass through the body. If nothing in the body changes what the condition looks at, the answer never changes, and the loop never ends. The values the condition depends on are the loop's state. A loop variable is a variable that holds part of that state, such as a counter.
A terminating loop has three parts:
- Initialize: give the state a starting value before the loop.
- Test: write a condition that reads the state.
- Update: change the state inside the body so the condition eventually becomes false.
n = 3 # initialize
while n > 0: # test
print(n)
n -= 1 # update
print("Liftoff")This prints 3, 2, 1 and then Liftoff. Each pass makes n smaller, and n > 0 fails once n reaches 0.
Move the state toward the exit
The update must push the state toward the point where the condition is false. Compare the condition with the direction of the update.
| Condition | Update that makes progress | Update that never ends the loop |
|---|---|---|
| `n > 0` | `n -= 1` | `n += 1` |
| `i < 10` | `i += 1` | `i -= 1` |
| `total < 100` | `total += amount` (with `amount > 0`) | `total += 0` |
The last row shows that the size of the step matters too. If amount can be zero or negative, total < 100 may never fail.
State is not always a counter
Any value the condition reads can be the state. The next loop counts the digits of a number by shrinking it.
n = 4096
digits = 0
while n > 0:
n //= 10
digits += 1
print(digits)Floor division drops the last digit each time, so n goes 4096, 409, 40, 4, 0. The loop prints 4. Note that the input 0 gives 0 digits, because the condition fails immediately.
A collection can also be the state. A non-empty list is truthy and an empty list is falsy, so you can loop until the list is empty.
tasks = ["write", "test", "ship"]
while tasks:
task = tasks.pop()
print("Doing", task)Each pop() removes the last item, so the loop prints ship, test, write and then stops. Here the update is the pop() call itself, and it is easy to overlook because it also produces a value you use.
Where to put the update
The update does not have to be the last line. You can place it first or in the middle, as long as every pass runs it. The choice changes which value the rest of the body sees.
- Update at the end: the body sees the value the condition just tested.
- Update at the start: the body sees the already-updated value. This is common when you need
continuelater in the body, because an early update cannot be skipped.
Because continue jumps straight back to the condition, any update placed after it is skipped. The continue chapter covers this in detail. For now, remember that an update that sits below a possible continue is not guaranteed to run.
Common ways the update goes wrong
- Wrong direction. The condition is
n > 0but the code doesn += 1. - Wrong variable. The condition tests
i, but the body changesj. - Update inside a branch. If the update sits in an
ifblock and the condition for that block can stay false forever, the state freezes. Withif i % 2 == 0: i += 1, a loop that reaches an oddinever moves again. - Update never reached. An early
continueskips it, as noted above. - Exact comparison with floats. Adding
0.1ten times does not give exactly1.0, sowhile x != 1.0can run forever.
The float problem has a simple fix: count with an integer and compute the float from it.
steps = 0
while steps < 10:
steps += 1
x = steps / 10
print(x)This always runs exactly ten times, because the integer steps counts exactly.
Exercise
This loop is meant to print 10, 7, 4, 1. It never stops. Find the bug and fix it. n = 10 while n > 0: print(n) n += 3
Show answer
The update moves n away from the exit, since n grows and n > 0 stays true. Change the update to n -= 3. The loop then prints 10, 7, 4, 1 and stops when n becomes -2.