1.2.17 · D5Introduction to Programming (Python)

Question bank — while loop — condition-based, infinite loop dangers

1,610 words7 min readBack to topic

Prerequisites worth having open: Boolean expressions and comparison operators (what a condition is), break and continue statements (how loops exit early), and Off-by-one errors (why the last check matters). Compare intent against the for loop.


True or false — justify

Every while loop body runs at least once.
False. The condition is checked before the first iteration (pre-test), so while False: runs the body zero times. This is the opposite of a do-while loop found in some other languages.
A while loop always ends.
False. It only ends if some code inside pushes the condition toward False. while True: with no break runs forever — that's an infinite loop by design or by accident.
The condition of while i <= 3: (starting i=1, i grows by 1) is evaluated exactly 3 times.
False. It's checked 4 times: three times it's True (printing 1, 2, 3) and once it's False (when i reaches 4), and that final failing check is what ends the loop.
while True: is always a programming mistake.
False. It's a standard, deliberate pattern — an intentionally endless loop that exits via a break. It's only a bug when the loop was meant to stop but nobody wrote an exit.
If a condition is True when the loop starts, changing the variable after the loop can stop it.
False. Only code inside the body affects an already-running loop. A line after the loop never executes until the loop has already exited, so it can't help.
A while loop and an equivalent for loop over range will always run the body the same number of times.
True-ish, but fragile. They can match, but the for loop's count is fixed by range, while the while depends on your update line being correct — one wrong update and the counts diverge.
Using and in a condition means both parts are always evaluated.
False. Python uses short-circuit evaluation: A and B skips B if A is already False. This matters when B would crash (e.g. dividing by zero) — order your conditions so the safe check comes first.

Spot the error

i = 0
while i < 5:
    print(i)

::: Missing update. Nothing ever changes i, so i < 5 stays True forever — an infinite loop printing 0 endlessly. Add i += 1 inside the body.

while count < 10:
    print(count)
    count += 1

::: count is never initialised. The very first check count < 10 reads a variable that doesn't exist yet → NameError. You must create count = 0 (the "Initialise" step) before the loop.

while x = 5:
    x -= 1

::: Assignment used as condition. = assigns, == compares. Python raises a SyntaxError — which is actually a lucky save, because it stops you before the loop can misbehave.

n = 3
while n > 0:
    print(n)
    if n == 2:
        continue
    n -= 1

::: Update skipped by continue. When n == 2, continue jumps back to the check before reaching n -= 1, so n sticks at 2 forever. The update must sit on the path that always runs. See break and continue statements.

x = 0.0
while x != 1.0:
    x += 0.1

::: Float never lands exactly on 1.0. Adding 0.1 in binary floating-point accumulates tiny errors, so x skips past 1.0 (e.g. to 0.9999... then 1.0999...) and != stays True forever. Use while x < 1.0: instead.

password = ""
while password != "open"
    password = input("Password: ")

::: Missing colon. Every while header ends with :. Without it Python raises a SyntaxError and the loop won't even start.

i = 10
while i > 0:
    print(i)
    i += 1

::: Update pushes the wrong direction. i starts at 10 and grows, so i > 0 only gets more true — infinite loop. To reach the stop condition you need i -= 1.


Why questions

Why is a while loop called a pre-test loop?
Because it tests (checks) the condition before running the body each time. "Pre" = before. This is why the body can run zero times if the condition starts False.
Why does forgetting the update line cause an infinite loop, even when the condition looks correct?
A variable in code changes only when a line of code changes it — unlike in math, values don't drift on their own. Without an update, the condition's variable is frozen and the answer to "still true?" never flips.
Why prefer while over for for reading user input until they type "quit"?
You don't know how many inputs the user will give — it depends on their behaviour, not a fixed count. for needs a known number of iterations; while loops on a condition, which is exactly "unknown count, stop when something happens". See input() and type conversion.
Why should you never compare floats with == in a loop condition?
Floating-point arithmetic stores values approximately, so a running sum rarely hits an exact target — it overshoots. Using < or > catches the boundary regardless of tiny rounding errors.
Why does an accumulator like while total < 100: total += x guarantee it stops?
Because total strictly increases every iteration (monotonic approach to the boundary). A value that always moves toward the limit must eventually cross it, flipping the condition to False.
Why is the final condition check (the one that fails) so important to count?
It's the check that actually ends the loop. Miscounting it is the source of off-by-one errors — you print one too many or too few items. See Off-by-one errors.
Why does break let us safely write while True:?
while True: can never end on its own, so break provides the real exit from inside the body — a controlled stop triggered by whatever event you choose, instead of by the condition. See break and continue statements.

Edge cases

What does while False: do?
Nothing — the body runs zero times. The condition fails on the very first pre-test check, so control skips straight past the loop.
What happens with while 1: (a number, not True)?
It loops forever, because any non-zero number is truthy in Python. 1 counts as True, so it behaves exactly like while True:.
What does while []: (an empty list) do?
Nothing — an empty list is falsy, so the condition is False immediately and the body never runs. Empty containers, 0, None, and "" are all falsy. See Boolean expressions and comparison operators.
In while n > 0: with n starting at exactly 0, how many times does the body run?
Zero. 0 > 0 is False right away, so it's a valid, deliberate "run only if there's work to do" — not a bug, just the boundary case.
If a break sits before the update line, does the update ever execute on that iteration?
No. break exits immediately, skipping every line below it — including the update. That's fine when you want to leave, but a trap if you expected cleanup code after break.
Can a while loop with a correct update still run forever?
Yes — if the update moves away from the condition (wrong direction/sign), or if a continue skips over it on some iterations. "Has an update line" is not the same as "reaches the stop condition".

Recall Self-test — cover the answers
  • Does while False: run its body? ::: No — pre-test fails first, zero iterations.
  • Why can't a line after the loop stop a running loop? ::: It only executes once the loop already exited; only body code affects a live loop.
  • Why is != dangerous with float updates? ::: Floats overshoot the exact target, so != stays true forever; use </>.
  • Is while 1: an infinite loop? ::: Yes — non-zero numbers are truthy, same as while True:.

Connections