Break and continue
Overview
Loops normally run every pass from start to finish. Two keywords give you finer control: break stops the loop early, and continue skips to the next pass. Together with the less-known loop else, they handle searches, filters and early exits cleanly.
break: stop now
break ends the loop immediately, even if there are items left or the while condition is still true:
for n in [1, 2, 3, 4, 5]:
if n == 3:
break
print(n)
print("after the loop")1
2
after the loopIt’s ideal for searching: once you’ve found what you want, there’s no point continuing.
for email in inbox:
if "urgent" in email.lower():
print("Urgent email found:", email)
breakAnd for the while True pattern from While loops: loop forever, break when done.
continue: skip this one
continue stops the current pass and goes straight to the next item (or back to the while condition):
for n in [1, 2, 3, 4, 5]:
if n % 2 == 0:
continue
print(n)1
3
5It’s handy for filtering out items you want to ignore, keeping the main logic un-indented:
for line in lines:
if not line.strip(): # skip blank lines
continue
if line.startswith("#"): # skip comments
continue
process(line)Without continue, the main work would sit inside nested ifs.
Loop else: “if I didn’t break”
Python loops can have an else block. It runs when the loop finishes normally — and is skipped if the loop ended with break:
for order_id, status, amount in orders:
if order_id == "A-999":
print("Found it")
break
else:
print("Order A-999 not found")Think of it as “no break”. It’s perfect for searches: the else is the “not found” case, without needing an extra found = False variable.
The name is admittedly confusing — many experienced programmers prefer a flag variable or a function with return. Use whichever your team finds clearest, but recognise the pattern when you see it.
Nested loops
break and continue only affect the innermost loop they’re in:
for row in grid:
for cell in row:
if cell == "X":
break # leaves only the inner loop
# the outer loop carries on with the next rowTo stop both loops, either use a flag:
found = False
for row in grid:
for cell in row:
if cell == "X":
found = True
break
if found:
breakor, more neatly, put the loops in a function and return from it (Return values and scope).
Use them wisely
break and continue make many loops simpler. But a loop with several of each, scattered through nested ifs, is hard to follow. If that happens, try:
- moving the condition into the
whileitself, - filtering the items first, then looping,
- moving the loop into a function with an early
return.
Remember:
break= “I’m done with this loop”,continue= “I’m done with this item”, loopelse= “the loop ran to the end without a break”.
Search an order history
Given a list of orders as (id, status, amount) tuples: (1) print the total amount of all orders, skipping cancelled ones with continue; (2) find the first order over 100 and print its id, stopping the search with break; (3) look for an order with id A-999 and use a for/else to print Order A-999 not found if the loop finishes without finding it.
orders = [
("A-101", "shipped", 40.0),
("A-102", "cancelled", 250.0),
("A-103", "shipped", 120.0),
("A-104", "pending", 75.5),
("A-105", "shipped", 310.0),
]
# 1. Total of non-cancelled orders (continue)
# 2. First order over 100 (break)
# 3. Search for A-999 with for/elseorders = [
("A-101", "shipped", 40.0),
("A-102", "cancelled", 250.0),
("A-103", "shipped", 120.0),
("A-104", "pending", 75.5),
("A-105", "shipped", 310.0),
]
# 1. Total of non-cancelled orders (continue)
total = 0
for order_id, status, amount in orders:
if status == "cancelled":
continue
total += amount
print("Total:", total) # 545.5
# 2. First order over 100 (break)
for order_id, status, amount in orders:
if amount > 100:
print("First big order:", order_id) # A-102
break
# 3. Search for A-999 with for/else
for order_id, status, amount in orders:
if order_id == "A-999":
print("Found it")
break
else:
print("Order A-999 not found")Summary
breakleaves the innermost loop immediately; the code after the loop runs next.continueskips the rest of the current pass and moves on to the next item.- A loop’s
elseblock runs only if the loop finished without hittingbreak— perfect for searches. breakandcontinueonly affect the innermost loop; to stop nested loops, use a flag or a function.- Use them to simplify loops, not to tangle them — sometimes a clearer condition is better.