break, continue & Loop else
Three statements fine-tune how loops run: break exits a loop early, continue skips to the next pass, and a loop's else block runs only if the loop finished without hitting break. Together they express common search-and-filter patterns cleanly.
break
orders = [120, 45, 300, 80, 999, 60] for amount in orders: if amount > 500: print(f"Suspicious order {amount} — stopping review") break print("Approved", amount)
Approved 120 Approved 45 Approved 300 Approved 80 Suspicious order 999 — stopping review
After break, the loop ends immediately and the program continues after it. The last order (60) is never reviewed.
continue
readings = [21.5, None, 22.1, -999, 23.4] total = 0 count = 0 for value in readings: if value is None or value == -999: continue total += value count += 1 print(f"Average of {count} valid readings: {total / count:.2f}")
Average of 3 valid readings: 22.33
continue is a clean way to skip invalid items without wrapping the rest of the loop in an if block.
break in nested loops
break only exits the innermost loop. To stop everything, put the loops in a function and return:
grid = [
[5, 3, 8],
[1, 42, 7],
[9, 2, 6],
]
def find(grid, target):
for r, row in enumerate(grid):
for c, value in enumerate(row):
if value == target:
return r, c
return None
print(find(grid, 42))
print(find(grid, 100))
(1, 1) None
Loop else
A for or while loop can have an else block. It runs when the loop ends normally — that is, without a break:
def check_password(password): for ch in password: if ch.isdigit(): print(f"{password!r}: contains a digit ✓") break else: print(f"{password!r}: needs at least one digit") check_password("secret7") check_password("secret")
'secret7': contains a digit ✓ 'secret': needs at least one digit
Think of it as "no break". It's perfect for searches: the else handles the "not found" case without needing a separate found = False flag.
primes = [] for n in range(2, 20): for divisor in range(2, int(n ** 0.5) + 1): if n % divisor == 0: break else: primes.append(n) print(*primes)
2 3 5 7 11 13 17 19
The inner loop breaks as soon as it finds a divisor; only numbers with no divisor reach the else and are collected as primes.
while … else
attempts = 0 codes = ["1111", "2222", "9999"] while attempts < 3: guess = codes[attempts] attempts += 1 if guess == "1234": print("Unlocked!") break else: print("Locked out after", attempts, "attempts")
Locked out after 3 attempts
pass, continue and break compared
| Statement | Effect |
|---|---|
pass | Does nothing — a placeholder where a statement is required |
continue | Skips the rest of this pass; the loop carries on |
break | Leaves the loop entirely; its else doesn't run |
return | Leaves the whole function, and therefore every loop inside it |
Often there's a shorter way
Many search loops can be replaced with built-ins:
numbers = [4, 9, 16, 25] print(any(n > 20 for n in numbers)) print(next((n for n in numbers if n % 2 == 1), None)) print(next((n for n in numbers if n > 100), "none found"))
True 9 none found
next(…, default) returns the first matching item, or the default if there isn't one — a compact alternative to a loop with break.