Chapter 2 · Apprentice

while loops

A while loop repeats its body as long as a condition stays true. Before each pass it checks the condition; the moment it's false, the loop ends and the program continues after it.

Reach for while when you don't know up front how many times you'll loop — "keep going until the user quits", "retry until it succeeds", "count down until we hit zero". Something inside the loop must eventually make the condition false, or it runs forever (an *infinite loop*).

break exits the loop immediately; continue skips to the next check. A common shape is a counter you change each pass so the loop terminates.

Syntax

while condition:
    # body — runs while condition is true
    # something here must eventually make condition false

# break  → leave the loop now
# continue → jump back to the condition check

Worked examples

Countdown with a changing counter

def countdown(n):
    result = []
    while n >= 1:
        result.append(n)
        n = n - 1        # this is what eventually stops the loop
    return result

print(countdown(3))   # [3, 2, 1]

break to stop early

total = 0
n = 1
while True:                # looks infinite...
    total += n
    if total > 10:
        break              # ...but break ends it
    n += 1
print(total)   # 15  (1+2+3+4+5)

continue to skip a pass

n = 0
kept = []
while n < 5:
    n += 1
    if n == 3:
        continue       # skip 3
    kept.append(n)
print(kept)   # [1, 2, 4, 5]

Common mistakes & gotchas

Infinite loops

If nothing in the body makes the condition false, the loop never ends. The classic cause is forgetting to update the counter (n = n - 1). If a program hangs, suspect a while loop with no exit.

Off-by-one in the condition

while n >= 1 includes 1; while n > 1 stops at 2. One character changes whether the last value is processed. Trace the first and last pass by hand when the boundary matters.

continue can skip the counter update

If you continue *before* incrementing the counter, you can accidentally loop forever. Update the counter early, or make sure every path reaches it.

Why it matters

Whenever the number of repetitions depends on what happens at runtime — retries, polling, reading until end-of-input, game loops — `while` is the tool. It's the loop of "keep trying until".