Python While Loops
Core idea
Use while condition: followed by an indented body when repetition depends on changing state. Python checks the condition before each iteration (one execution of the body). If the condition is false at the start, the body never runs. Choose an initial value and an update that eventually makes the condition false.
remaining = 3while remaining > 0: print(remaining) remaining = remaining - 1print("Ready")The body prints 3, 2 and 1. After the last subtraction, remaining is 0; the next test fails and the unindented print runs once.
Fill to a target
volume = 2while volume < 10: volume = volume + 3print(volume)The volumes are 2, 5, 8 and 11. The condition stops at the first value at least 10; the update can overshoot the target.
Zero iterations
stock = 0while stock > 0: print("Pack item") stock = stock - 1print("Done")The initial condition is false, so no item is packed.
Common mistake
Leaving the update out of the countdown would keep the condition true forever. Do not run that broken version. Check whether each possible path through the body makes progress toward termination.
Practice
Start with 12 units and remove 4 per iteration until none remain. Predict each state, then repeat with an initial value of 0.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
While loop state and termination
Check your understanding of while loops.
What is printed?
n = 2while n > 0: print(n) n = n - 1What is printed?
n = 0while n > 0: n = n - 1print(n)What final value is printed?
n = 3while n < 10: n = n + 3print(n)Which change makes a countdown starting at 5 with condition n > 0 finish?