Python break & continue
In this page:
for item in iterable:
if condition:
break # exit loop
if other_condition:
continue # skip to next item
The Break Statement
break immediately exits the nearest enclosing loop, skipping any remaining iterations entirely — useful the moment you've found what you were searching for and there's no reason to keep checking the rest.
Example: The Break Statement
for n in [1, 2, 3, 4]:
if n == 3:
break # exits the loop immediately, 4 is never reached
print(n)
The Continue Statement
continue skips only the rest of the current iteration and jumps straight to the loop's next check, rather than ending the loop entirely the way break does — handy for filtering out cases you want to ignore without restructuring the loop body around an if.
Example: The Continue Statement
for n in [1, 2, 3, 4]:
if n == 2:
continue # skips printing 2, then moves to the next iteration
print(n)
While Loop with Break
Combining break with a while True: loop is a common pattern for "loop until some condition is met," letting the exit condition live anywhere inside the loop body instead of only in the loop's header.
Example: While Loop with Break
while True: # loop with no condition, relies on break to end
print("Looping once")
break # exits immediately after the first pass
While Loop with Continue
When using continue inside a while loop, make sure any counter update happens *before* the continue line — otherwise the counter never advances for skipped iterations, and the loop runs forever.
Example: While Loop with Continue
i = 0
while i < 5:
i += 1 # counter updated before continue, so the loop still progresses
if i == 3:
continue # skips the print below only for this iteration
print(i)
Else Block in Loops
A loop's optional else block runs only if the loop finished all its iterations without ever hitting a break — a lesser-known feature that's useful for search loops where you want to know whether the target was actually found.
Example: Else Block in Loops
for n in [1, 2, 3]:
if n == 5:
break
else: # runs only if the loop finished without hitting break
print("Never broke out")
- Expecting
breakto exit all nested loops; it only exits the innermost one. - Putting
continuebefore the counter update in awhileloop, causing an infinite loop. - Misreading the loop
else: it runs only when the loop ends withoutbreak, not when it fails.
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: