CodeMIRAI
0 XP

break, continue and loop else

2 min read 4 runnable examples Quiz included

Sometimes you want to stop a loop early, or skip one item and carry on. That's what break and continue do.

break: leave the loop now

break exits the loop immediately, even if items remain:

Python
numbers = [4, 7, 12, 9, 15, 3]
for n in numbers:
    if n > 10:
        print("First number over 10:", n)
        break
    print("Checked", n)

The loop stops at 12, so 9, 15 and 3 are never checked.

continue: skip to the next round

continue skips the rest of the current iteration and moves straight to the next item:

Python
for n in range(1, 11):
    if n % 3 == 0:
        continue        # skip multiples of 3
    print(n, end=" ")

Both in a while loop

Python
total = 0
while True:
    entry = input("Enter a positive number or 'quit': ")
    if entry == "quit":
        break                 # stop completely
    if not entry.isdigit():
        print("  skipping", entry)
        continue              # ignore this one, ask again
    total += int(entry)
print("Total:", total)

The loop else clause

A for or while loop can have an else block. It runs only if the loop finished without hitting break. This is perfect for searches:

Python
def find_divisor(n):
    for d in range(2, n):
        if n % d == 0:
            print(f"{n} is divisible by {d}")
            break
    else:
        print(f"{n} is prime")

find_divisor(91)
find_divisor(97)

Read the else as "if no break". Without it you would need an extra found = False variable.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.