break & continue

Exit a loop early or skip an iteration.

Syntaxbreak continue

Two 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

Try it yourself
Loading editor…
Press Run to execute the code.

When 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.

Example · python
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, stopping

continue skips an iteration

Uses continue to jump back to the loop header for even numbers, printing only odd ones.

Example · python
for i in range(1, 8):
    if i % 2 == 0:
        continue   # skip even numbers
    print(i)

# Output:
# 1
# 3
# 5
# 7

break and continue together

Skips empty strings with continue and halts the entire loop on a sentinel value with break.

Example · python
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

  • Be the first to comment on this lesson.