Sub topic 1
How a while loop works
A while loop repeats a block of code for as long as a condition stays true. This chapter builds the working model: how Python runs the loop, in what order, and which mistakes show up first.
Prerequisites
This chapter assumes you already know:
- Variables and assignment
- Comparison and boolean operators such as
>,==,and, andnot ifstatements and how indentation marks a block- Basic use of
printandinput
The shape of a while statement
A while statement has a header and a body.
while condition:
bodyThe header is the keyword while, an expression, and a colon. The body is the indented block under it. Python runs the body again and again until the condition is false.
The execution model
Python follows the same steps every time:
- Evaluate the condition.
- If it is true, run the whole body once, then go back to step 1.
- If it is false, skip the body and continue with the first line after the loop.
The condition is checked before every pass, including the first one. It is not checked in the middle of the body. If the condition becomes false halfway through a pass, the rest of that pass still runs.
A first example
This loop counts down from 3.
n = 3
while n > 0:
print(n)
n -= 1
print("Liftoff")It prints 3, 2, 1, and then Liftoff. The table shows what happens at each check.
| Check | Value of `n` | `n > 0` | Result |
|---|---|---|---|
| 1 | 3 | True | Print 3, then `n` becomes 2 |
| 2 | 2 | True | Print 2, then `n` becomes 1 |
| 3 | 1 | True | Print 1, then `n` becomes 0 |
| 4 | 0 | False | Leave the loop |
The body ran three times, but the condition was evaluated four times. The last check is the one that ends the loop. Remember this count of "bodies plus one" when you trace a loop by hand.
A loop may run zero times
Because the check comes first, a loop whose condition starts out false never runs its body.
n = 0
while n > 0:
print("This never prints")
print("Done")This is useful. Code such as "process everything in the queue" works correctly even when the queue is empty, because the loop simply does nothing.
The three parts of a working loop
Most while loops that behave well have three parts:
- Initial state. A variable is set up before the loop (
n = 3). - Condition. An expression uses that variable (
n > 0). - Update. The body changes the variable so the condition can eventually become false (
n -= 1).
If any one of these is missing or wrong, the loop misbehaves. A missing initial state raises a NameError when Python first evaluates the condition. A missing or wrong update gives you a loop that never ends.
Variables keep their values afterward
A while loop does not create a new scope. Variables assigned in the body or header remain available after the loop finishes.
total = 0
k = 1
while k <= 4:
total += k
k += 1
print(total)
print(k)This prints 10 and then 5. The value of k is 5, not 4, because the loop only ended after k was incremented and the check 5 <= 4 failed. Off-by-one surprises like this are common when you use the counter after the loop.
Common errors at this stage
- Forgetting the update. If
n -= 1is removed from the countdown,nstays 3 and the loop runs forever. Press Ctrl+C to stop a runaway program. - Updating in the wrong direction. Writing
n += 1in the countdown makesngrow, son > 0never becomes false. - Using
=instead of==. Writingwhile n = 3:is a syntax error. Use==to compare. - Off-by-one conditions.
n >= 0prints a final0, whilen > 0does not. Decide whether the boundary value should be included, then test the first and last pass. - Indenting the update outside the body. If
n -= 1is not indented, it is not part of the loop, and the loop never changesn.
Tracing a loop by hand
To predict output, write down the variables and update them line by line, as in the table above. Then check the condition against the new values. This habit works for any loop, and it catches update errors before you run the code.
Exercise
What does this code print, and how many times is the condition evaluated? x = 10 while x > 4: x -= 3 print(x)
Show answer
It prints 7 and then 4, and the condition is evaluated three times. The checks are 10 > 4 (true, x becomes 7, print 7), 7 > 4 (true, x becomes 4, print 4), and 4 > 4 (false, the loop ends).
Exercise
A loop starts with count = 5 and the header while count < 5:. How many times does the body run, and why?
Show answer
Zero times. Python checks the condition before the first pass, and 5 < 5 is false, so the body is skipped.