Break and continue

Topic 3 of 4 in Loops5 min readBeginnerFree course

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 and continue. continue skips to the next item: with if n % 2 == 0: continue, the items 1 to 5 are processed except 2 and 4, so it prints 1 3 5 (skipped items are dashed). break leaves the loop now: with if n == 3: break, it prints 1 2 and the loop stops at 3, so 4 and 5 are never reached.

break: stop now

break ends the loop immediately, even if there are items left or the while condition is still true:

Python
for n in [1, 2, 3, 4, 5]:
    if n == 3:
        break
    print(n)
print("after the loop")
Text
1
2
after the loop

It’s ideal for searching: once you’ve found what you want, there’s no point continuing.

Python
for email in inbox:
    if "urgent" in email.lower():
        print("Urgent email found:", email)
        break

And 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):

Python
for n in [1, 2, 3, 4, 5]:
    if n % 2 == 0:
        continue
    print(n)
Text
1
3
5

It’s handy for filtering out items you want to ignore, keeping the main logic un-indented:

Python
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:

Python
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:

Python
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 row

To stop both loops, either use a flag:

Python
found = False
for row in grid:
    for cell in row:
        if cell == "X":
            found = True
            break
    if found:
        break

or, 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 while itself,
  • 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”, loop else = “the loop ran to the end without a break”.

Exercise

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.

Python
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/else

Summary

  • break leaves the innermost loop immediately; the code after the loop runs next.
  • continue skips the rest of the current pass and moves on to the next item.
  • A loop’s else block runs only if the loop finished without hitting break — perfect for searches.
  • break and continue only 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.