Reading — step 1 of 8
Learn
A for loop is perfect when you know in advance how many times to repeat. But sometimes you DON'T know how many iterations you'll need. "Keep asking until the user types 'quit.'" "Keep retrying until the network call succeeds." "Keep guessing until the answer is right." That's where while loops come in.
The shape of a while loop
The header reads: "WHILE this condition is True, run the indented body." Python checks the condition BEFORE each iteration. If it's True, run the body. If it's False, skip to the next statement after the loop.
Three pieces matter:
- The keyword
while. - A condition (anything that evaluates to a boolean).
- A colon and indented body — and something inside the body must eventually make the condition False, or you have an infinite loop.
When for won't do — input until a sentinel
while True is an idiom for "loop until I explicitly break out." Combined with a break statement on a condition, it's how you handle "keep going until X."
break — exit the loop immediately
When break runs, control jumps to the line AFTER the loop. The remaining iterations are skipped entirely. break works in both for and while.
continue — skip to the next iteration
continue says "don't finish the rest of this iteration, jump back to the top."
continue is occasionally clearer than nesting with if. Use it sparingly — too many continues in one loop become hard to follow.
The else clause on loops (uncommon but useful)
Python lets you attach else to a while or for loop. The else runs ONLY if the loop completed without hitting a break:
Not many languages have this. It's awkward at first but elegant once you've seen it a few times.
The infinite-loop trap
This kind of bug eats CPU and prints the same line forever. To stop a runaway program in your editor, press the stop button (or Ctrl+C in a terminal). Always ask: what changes inside this loop body that could eventually make the condition False? If nothing does, you have a bug.
When to use for vs while
- for — the COUNT or COLLECTION is known up front. "For each item in this list…" "Repeat 10 times…"
- while — the END CONDITION is dynamic. "Until the user types quit…" "As long as the file has more lines…" "While we haven't found the answer…"
If you find yourself manually counting in a while, a for is often cleaner.
Common mistakes
- Forgetting to update the loop variable — instant infinite loop.
- Off-by-one in the condition:
while i < 5runs 5 times when starting from 0;while i <= 5runs 6 times. Be deliberate. - Reading input forever:
while True: line = input()will block if stdin runs out (in a script context). Always have a clear termination. - Overusing
break/continue— readable code keeps the loop body simple. Refactor before piling on jumps.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…