Command Palette

Search for a command to run...

Hectal
PHASE 2Beginner ~25 min· topic 5 of 9

Topic 2.5

break, continue and the Loop else

In one line

break leaves a loop at once, continue skips the rest of the current pass, and the unusual else on a loop runs only when the loop finished without a break. Together they express searching and early exit cleanly.

Think of it like this

Looking for your keys in a row of drawers. You open drawer after drawer. When you find the keys you stop searching at once (that is break). If a drawer is locked you skip it and try the next (that is continue). If you opened every drawer and never found them, you say "not here" (that is the loop else).

Words you'll meet

New words in this topic, in plain English. Come back here whenever one feels fuzzy.

break
Leaves the nearest loop immediately.
continue
Skips the rest of the current pass and goes on to the next one.
Loop else
An else block after a loop that runs only if the loop finished without hitting break.
Early exit
Stopping a loop (or a function) as soon as the answer is known.
Search pattern
Loop through candidates, break on a match, use the loop else for "not found".
Flag variable
A variable such as found = False used to remember whether something happened.
Divisor
A number that divides another exactly, leaving no remainder.
Prime number
A whole number above 1 whose only divisors are 1 and itself.

Step by step

01break: stop the whole loop

The loop prints items until it meets one bigger than 10, then break jumps to the line after the loop. The 7 at the end is never looked at.

main.pywhole filepython
for n in [3, 8, 5, 12, 7]:
    if n > 10:
        print("Too big, stop at", n)
        break
    print("Handling", n)
print("Loop finished")

02continue: skip just this pass

For an even number the code prints a message and continue jumps to the next item, so "Handling" is not printed for it. The loop itself goes on.

main.pywhole filepython
for n in [3, 8, 5]:
    if n % 2 == 0:
        print(n, "is even, skip")
        continue
    print("Handling", n)
continue: skip just this passdiagram
Rendering diagram…

03Both together

The five-number list in the first example below uses both. Follow it by hand: 3 is handled, 8 is even and skipped, 5 is handled, 12 is too big so the loop breaks, and 7 is never reached.

04The loop else: runs when there was no break

In the first loop nothing matches, so there is no break, the loop ends because the items ran out, and the else block prints. If "Ben" were the wanted name, break would skip the else.

main.pywhole filepython
names = ["Asha", "Ben", "Chen"]
wanted = "Dev"
for name in names:
    if name == wanted:
        print("Found", name)
        break
else:
    print(wanted, "is not in the list")     # runs only if no break

05Prime check with for/else

A number is prime if no divisor from 2 up to just below it divides it exactly. The break records "found a divisor", and the else means "tried them all, none divided it". No flag variable is needed.

main.pywhole filepython
candidate = 21
for divisor in range(2, candidate):
    if candidate % divisor == 0:
        print(candidate, "is divisible by", divisor)
        break
else:
    print(candidate, "is prime")

06else also works on while

A while loop can have an else too, with the same meaning: it runs when the condition became False, not when a break left the loop. It is rare in practice.

main.pywhole filepython
tries = 0
while tries < 3:
    tries += 1
    if tries == 5:          # never true
        break
else:
    print("Finished all", tries, "tries without a break")

07A continue trap in while loops

In a while loop, continue jumps straight back to the condition, skipping the rest of the block. If the counter update is below the continue, it is skipped too, and the loop never ends. Update the counter first, or use for.

main.pywhole filepython
n = 0
while n < 5:
    if n == 2:
        continue        # BUG: n += 1 below is skipped, n stays 2 forever
    print(n)
    n += 1

Try it yourself

  1. 1

    Move the break

    In the first example, move the if n > 10 check below the if n % 2 == 0 block. Run it. The loop no longer breaks at 12. Work out why: 12 is even, so continue skips it before the break test is reached.

  2. 2

    Find the first multiple of 7

    Loop over [12, 25, 49, 50, 56]. Print the first multiple of 7 you find and stop. Predict the answer (49) first, then use break.

  3. 3

    else or flag?

    Rewrite the prime check with a flag variable (is_prime = True, set it to False before break, test it after the loop). Compare it with the loop else version. Which is shorter, and which would a new reader find clearer?

Code & diagrams

break and continue together New tab

Change 12 to 9 and run again: the loop no longer breaks, so every number is handled.

Sign in to run this example in your browser.

Expected output

Handling 3
8 is even, skip
Handling 5
Too big, stop at 12
Loop finished
Searching with the loop else New tab

Change wanted to "Ben" and watch the else block disappear. In the prime part, try 2, 1 and 49: what do you get for 1, and why? (The range is empty, so nothing breaks.)

Sign in to run this example in your browser.

Expected output

Dev is not in the list
29 is prime
21 is divisible by 3

Break it on purpose

Errors are the best teachers. Make each change, read the error, guess what went wrong, then reveal the answer.

Break #1

break outside a loop

Use break in an if that is not inside any loop.

main.pywhole filepython
total = 0
if total == 0:
    break
terminal
$ python main.py
── what you'll see ──
File "main.py", line 3
SyntaxError: 'break' outside loop

Myth vs fact

Myth

The loop else runs when the loop is empty or when something fails.

Fact

It runs when the loop was **not ended by break**: the items ran out or the while condition became False. An empty loop runs the else too.

Myth

break leaves all loops at once.

Fact

It leaves only the nearest loop. An outer loop continues with its next pass.

Myth

continue ends the loop.

Fact

It ends only the current pass. The loop then goes on to the next item or condition test.

Myth

You can't search a list without a flag variable.

Fact

A loop else (or any() and in, which you will meet later) does it with no flag.

Pro corner

Extra depth for experienced readers. New to this? Skip it for now and come back later.

  • ▸

    The Python language reference spells the loop else clause out: it executes when the loop terminates through exhaustion of the iterable (for) or when the condition becomes false (while), but not when the loop is terminated by break. Because the name is confusing, a short comment such as # no break is considered good practice.

  • ▸

    For simple searches, Python has better tools than a hand-written loop: x in items, any(...) and next((x for x in items if cond), default). Reach for a for/else when the loop needs more than one statement of work per candidate.

  • ▸

    A return inside a loop (Topic 5.10) is often a cleaner early exit than break plus code after the loop, because it ends the whole function at the moment the answer is known.

  • ▸

    Inside try/finally (Topic 7.1), a break, continue or return still runs the finally block first, so cleanup is never skipped by an early exit. For the prime check, range(2, candidate) is slow for big numbers: divisors come in pairs, so range(2, math.isqrt(candidate) + 1) is enough (and candidate < 2 must be rejected first, since 0 and 1 are not prime).

  • ▸

    break and continue are compiled to plain jump instructions in the bytecode (Topic 13.3), so they cost almost nothing. Using them for readability is free; the cost of a loop is in what its body does.

Remember this

  1. 1

    break ends the nearest loop (the one it is directly inside) immediately. Python jumps to the first line after the loop, even if the loop's condition is still True or items are still left. Use it when the job is done early: you found what you wanted, hit an error value, or got a stop signal.

  2. 2

    continue ends only the current iteration. Python jumps straight to the next pass: back to the condition in a while, or to the next item in a for. Use it to skip items you don't want to process, which keeps the main work un-indented instead of wrapped in a big if.

  3. 3

    Both work on the nearest loop only. In a loop inside a loop, break leaves the inner one and the outer one carries on (Topic 2.7 shows ways to leave both). They are only allowed inside a loop: anywhere else Python gives SyntaxError: 'break' outside loop.

  4. 4

    Loops can have an else block, and its name is confusing. Read it as "no break": the else block runs when the loop ended normally (the items ran out or the condition became False), and it is skipped when a break ended the loop. It is not "else if the loop was empty".

  5. 5

    The loop else is made for the search pattern: loop over the candidates, break when one matches, and put the "nothing matched" code in else. It replaces a flag variable such as found = False that you would otherwise set, test and forget to reset. A good example is a prime check: if no divisor breaks the loop, the number is prime.

  6. 6

    Do not overuse these. A loop with several breaks and continues can be harder to follow than one with a clear condition. A good rule: use continue to skip uninteresting cases at the top of the block, use break for the one clear exit, and keep the loop else for searches where its meaning is obvious (add a short comment such as # no break).

Explain it without notes

01

What is the difference between break and continue?

02

When does the else block of a for loop run?

03

How do you search a list for a value using for/else, and why is that nicer than a flag?

04

Why can continue cause an infinite loop in a while loop?

Practice

01

Loop over [12, 25, 49, 50, 56] and print the first number divisible by 7, then stop. Output: First multiple of 7: 49.

02

Add up the positive numbers in [3, -1, 4, -5, 2], skipping negatives with continue. Print Total: 9.

03

Use for/else to check the password text "hello" for a digit (use letter.isdigit(), a text tool that gives True when letter is a digit; Phase 3 teaches such tools). Print No digit found if there is none.

Trade-offs

  • ↔

    Early exit vs single exit. break makes the finished condition obvious and saves work, but a loop with many exits is harder to reason about. Keep it to one clear break.

  • ↔

    Loop else vs flag. The loop else is shorter, but its name is confusing for people who have not seen it. A comment, or a flag in team code that is unfamiliar with it, may be the kinder choice.

Done when you can

  • Done when you can say what break and continue do and which loop they affect.

  • Done when you can read the loop else as "no break".

  • Done when you can write the search pattern and the prime check with for/else.

  • Done when you can spot the continue trap in a while loop.