Repeat While It Holds
A while loop repeats its body as long as a condition stays true, so the body must eventually make that condition false. · 12 min
Until now, every line of your program has run at most once. A while loop breaks that limit. It reads a test, and as long as the test is True, it runs a block of lines called the body, then goes back and checks the test again. Run, recheck, run, recheck — the loop keeps circling until the test finally comes out False. That last part is the whole responsibility of a while loop: something inside the body must change, step by step, until the condition stops being true. If nothing changes, the loop circles forever, and the program never moves on.
Guess before you learn
Read this loop before you run it in your head:
count = 1
while count <= 3:
print(count)
count = count + 1
What is the last number it prints?
The loop prints 1, then 2, then 3. When count reaches 4, the test 4 <= 3 is False, so the loop stops before printing 4. If you guessed 4, keep that pencil mark: expecting the loop to run one more time is the classic off-by-one slip, and this folio is built around finding exactly where a loop stops.
9–12
3–5
A while loop repeats a block of lines for as long as a question stays true. while count < 5: keeps running the lines under it while count is still below 5.
For the loop to end, something in the body must change the answer. If count never grows, count < 5 stays true forever and the loop never stops. That runaway is called an infinite loop.
6–8
A while loop has a header — the keyword while, a condition, and a colon — and an indented body beneath it. Python checks the condition; if it is True, it runs the body once, then checks the condition again. It keeps repeating until the condition is False, and only then moves past the loop.
The body must eventually make the condition false. The usual pattern has three parts: set a counter before the loop, test it in the condition, and change it inside the body. Miss the change and you get an infinite loop — the body runs forever because nothing ever ends it.
9–12
Three ingredients make a well-formed counting loop: an initialisation before the loop, a condition tested each pass, and an update inside the body that moves toward making the condition false. i = 0 / while i < n: / i = i + 1 is the template.
The loop runs as long as the condition holds, so to be sure it ends you check that each pass brings the condition closer to false. A loop with no such progress — a forgotten update, or a condition that can never fail — never terminates.
K–2
While means keep going as long as something is true. While your cup is not full, keep pouring. The moment it is full, you stop. You check, you pour, you check again.
Each time, one thing changes: the cup gets a little more full. That change is what finally makes you stop. If the cup never filled, you would pour forever.
Undergrad
The while loop is the general iteration primitive: it expresses repeat this while the guard holds with no built-in notion of counting. Anything you can iterate, you can iterate with while, by managing the state yourself.
Two ideas control it. A loop invariant is a statement true before and after every pass, used to prove the loop computes the right thing. A variant is a quantity that strictly decreases each pass toward a bound, used to prove the loop ends at all.
Postgrad
Partial correctness and termination are separate obligations. An invariant that holds on entry and is preserved by the body establishes what the loop computes if it halts; total correctness additionally requires a variant — a well-founded measure that strictly decreases each iteration — to guarantee it halts.
Termination in general is undecidable, which is why the compiler cannot warn you about an infinite loop. For any particular loop, though, exhibiting a decreasing measure bounded below is a finite, checkable proof that it stops — the discipline this lesson introduces informally as the body must make the condition false.
loop body
The indented block of lines beneath a while header. Python runs the whole body each pass, then rechecks the condition.
The danger and the discipline are the same fact seen twice: a while loop runs until its condition turns false, so you must build that turn into the body. The most common shape is a counter — a variable that starts at one value and climbs or falls a fixed step each pass. Watching that counter change, pass by pass, is how you predict when the loop ends.
Trace this loop, one pass at a time — the steps fade as you master them
i = 1, total = 0. Test i <= 3 is True, so run the body. First line: total = total + i = 0 + 1. What is total now?total = 1
i = i + 1. What is i now?i = 2
2 <= 3 is True. Run the body again: total = total + i = 1 + 2. What is total now?total = 3
i is 4 and total is 6. Recheck: 4 <= 3 is False, so the loop ends. What is the final value of total?total = 6
Why is this true?
Why can a while loop run zero times — not even once?
Because the condition is tested before the first pass, not after. If it is already false when the loop is reached, Python skips the body entirely and moves on. A while loop runs its body only while the test is true, and while can mean never if it starts out false.
A while loop is the honest workhorse of repetition: it runs while a condition holds and stops the instant it does not. It asks nothing about how many times — only whether to go again. When you do know the count in advance, there is a tidier tool. The next folio introduces the for loop, which runs the body once for each item in a sequence.
Note
Losing the thread of a loop mid-trace? The Atelier of Mind drills trace tables until reading a loop pass by pass feels automatic.
Practice — new ink and old, interleaved
1.Review from folio 5: (4 >= 4) and (2 < 1) evaluates to?
2.How many numbers does this loop print?
n = 3
while n > 0:
print(n)
n = n - 1
3.Evaluate 10 % 3, the remainder of 10 divided by 3.
4.(4 < 2) or not (3 == 3) evaluates to?
5.Trace: what is x after this loop?
x = 2
while x < 20:
x = x * 2
6.Review from folio 6: x = 4. if x > 10: print('big') / elif x > 2: print('medium') / else: print('small'). What prints?
7.Without looking back: in an if / elif / else chain, which branch runs, and what does else do?
The branch under the first test that is True runs, and only that one; else runs when every test above it was False.
How close were you? Grade yourself honestly — it sets your review date.
8.Say in your own words when a while loop stops running.
A while loop stops as soon as its condition is tested and found false; until then it runs its body again and again.
How close were you? Grade yourself honestly — it sets your review date.
9.Evaluate 10 % 3 (the remainder).