break & continue
Exit a loop early or skip an iteration.
Syntax
break
continueTwo keywords give you fine control inside loops:
break— stops the loop completely.continue— skips the rest of the current pass and moves to the next.
A loop can also have an else block that runs only if the loop finished without hitting break.
Example
for i in range(1, 11):
if i == 6:
break
if i % 2 == 0:
continue
print(i)
# Output:
# 1
# 3
# 5When to use it
- A search function uses break to stop iterating the moment the target item is found.
- A log parser uses continue to skip blank lines and only process lines with content.
- A rate limiter breaks out of a send loop once the per-second message quota is reached.
More examples
break exits a loop early
Loops through numbers and stops immediately when the value 9 is encountered.
numbers = [3, 7, 2, 9, 1, 5]
for n in numbers:
if n == 9:
print('Found 9, stopping')
break
print(n)
# Output:
# 3
# 7
# 2
# Found 9, stoppingcontinue skips an iteration
Uses continue to jump back to the loop header for even numbers, printing only odd ones.
for i in range(1, 8):
if i % 2 == 0:
continue # skip even numbers
print(i)
# Output:
# 1
# 3
# 5
# 7break and continue together
Skips empty strings with continue and halts the entire loop on a sentinel value with break.
data = ['ok', '', 'ok', 'STOP', 'ignored']
for item in data:
if item == '':
continue # skip blank entries
if item == 'STOP':
break # halt processing
print('Processing:', item)
# Output:
# Processing: ok
# Processing: ok
Discussion