Break, Continue, and Loop Else
Exiting loops early, skipping an iteration, and the surprising else clause loops can have.
2 min read
Beyond the basic for and while, Python gives you finer control over what happens mid-loop — and one construct, the loop else, that doesn't exist in most other languages at all.
break exits the loop immediately
numbers = [3, 7, 12, 9, 15]
for n in numbers:
if n > 10:
print(f"Found it: {n}")
breakOnce break runs, the loop stops entirely — no further iterations, no further condition checks. This is the standard way to stop searching once you've found what you're looking for, rather than looping through everything and checking a flag afterward.
continue skips to the next iteration
for n in range(10):
if n % 2 != 0:
continue
print(n) # prints only even numbers: 0, 2, 4, 6, 8continue skips the rest of the current pass and jumps straight to the next iteration, without exiting the loop the way break does. It's useful for filtering out cases you don't want to handle, without wrapping the entire loop body in a nested if.
The loop else clause
This one catches most people coming from other languages off guard: both for and while loops can have an else block, which runs only if the loop finished naturally — that is, it completed without hitting a break.
numbers = [1, 3, 5, 7, 9]
for n in numbers:
if n % 2 == 0:
print("Found an even number")
break
else:
print("No even numbers found")Think of it less as "else" and more as "then" — "loop through these, and then, if nothing interrupted you, do this." It's a clean way to express "search for something, and if you never found it, do X" without a separate flag variable:
found = False
for n in numbers:
if n % 2 == 0:
found = True
break
if not found:
print("No even numbers found")Both versions do the same thing, but the for/else version needs no extra found variable to track.
Combining them
for username in ["alice", "bob", "carol"]:
if username == "eve":
continue # skip anyone named eve
if username == "admin":
print("Reserved name found, stopping.")
break
print(f"Processing {username}")break, continue, and the loop else are small tools, but knowing them means you rarely need extra boolean flags or awkwardly nested conditionals just to control a loop's flow.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.