Python while Loops With break, continue and else
A while loop repeats its block as long as a condition stays true. Use it when you do not know in advance how many repetitions you need: reading input until the user types quit, retrying a network call, or running a game loop. When you are walking through a known collection, a for loop is simpler.
The loop must make progress
Python checks the condition before each pass. If it is true, the body runs and Python checks again. Something inside the body must eventually make the condition false; in the countdown below, count -= 1 does that. Forget it and you have an infinite loop. In a terminal, press Ctrl+C to stop one. count -= 1 is shorthand for count = count - 1; +=, *= and friends work the same way.
Expected output
Countdown: 3 Countdown: 2 Countdown: 1 Liftoff! 1 3 5 7 no word starts with z
break and continue
breakleaves the innermost loop immediately, skipping any remaining items or checks.continueskips the rest of the current pass and jumps back to the condition (or, in aforloop, to the next item).
A common pattern is while True: with a break inside, used when the exit test belongs in the middle of the loop rather than at the top. In the example, even numbers are skipped with continue, and the loop stops with break once n passes 7.
The else clause on loops
Both for and while loops accept an else block, which runs only if the loop finished without hitting break. It reads best as "no break". The last part of the example searches for a word starting with z; because no break happened, the else reports that nothing was found. Without it you would need an extra flag variable. Use it sparingly and comment it, since many readers do not expect it.
Common mistakes
- Forgetting to update the variable in the condition, creating an infinite loop.
- Placing
continuebefore the update line, so the update is skipped and the loop never ends. - Thinking loop
elseruns when the loop condition is false at the start only. It runs whenever the loop ends normally, including after many passes.
Summary
while cond:repeats whilecondis true and is checked before each pass.- Make sure every pass moves toward ending the loop.
breakexits;continueskips to the next pass.- A loop's
elseruns only when nobreakoccurred.
Quiz: while, break, continue