Until now, every line ran once. A loop lets one block of code run again and again — as long as a condition stays true. This is the single biggest jump in what your programs can do.
Read the while half today; we’ll hit for in 3.3.
Enrolled in our Runestone course? Open it from there so your progress counts.
Still in Programs, opening Unit 3 — the longest and most important unit of the year. Unit 2 taught the machine to decide; Unit 3 teaches it to repeat. Everything after this unit uses loops, lists, and procedures; nothing after it re-teaches them.
A while loop is exactly that: “keep
doing this while the condition is true.” The power — and the danger — is
that the computer will happily repeat forever if you never let the condition become false. Today
you learn to loop on purpose and stop on purpose.
A while loop has three parts, and every correct loop has all three:
| Part | What it is | In the example below |
|---|---|---|
| the condition | a Boolean checked before each pass | n > 0 |
| the body | the indented lines that repeat | print(n) |
| the escape hatch | a line that moves the condition toward false | n = n - 1 |
n = 3 while n > 0: print(n) n = n - 1 print("liftoff")
# start n at 3 # check n > 0 BEFORE each pass # body: prints 3, then 2, then 1 # escape hatch: n drops each time # when n hits 0, condition is # false → loop ends → "liftoff"
Hover or tap a line to light its twin. Output is 3, 2,
1, liftoff. The condition is checked before each pass, so when
n reaches 0 the body is skipped entirely.
if asks its condition once and runs its
block at most once. A while asks the same kind of condition over and over, running its
block each time the answer is still true. If you understood 2.12, you’re most of the way
here already.
Set a starting value and step through the countdown one pass at a time. Watch the condition get
checked before each body run, and the escape hatch shrink n toward zero.
while loop repeats as long as a condition
stays true.while loop), not a fixed
count.Five questions. Trace each loop on paper — write the variable after every pass — then pick your answer.
Almost every program you use is one big loop: a game redraws the screen while you’re playing; a server waits for requests while it’s running; your phone checks for messages while it’s on. “Do this repeatedly until something changes” is the shape of nearly all software.
It’s also how programs hang. When an app “stops responding,” a loop is often stuck — a condition that should have gone false never did. The same construct that gives software its power gives it its most common way to freeze. Respect the escape hatch.
while is an if that keeps asking. The
Boolean condition skill transfers directly.REPEAT UNTIL, and its
condition is the opposite of the while condition. That flip is a whole
lesson.