Python break & continue
In this page:
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
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
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:
print("Looping once")
break
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
if i == 3:
continue
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:
print("Never broke out")
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: