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
elseblock after a loop that runs only if the loop finished without hittingbreak. - 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 = Falseused 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.
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.
for n in [3, 8, 5]:
if n % 2 == 0:
print(n, "is even, skip")
continue
print("Handling", n)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.
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 break05Prime 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.
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.
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.
n = 0
while n < 5:
if n == 2:
continue # BUG: n += 1 below is skipped, n stays 2 forever
print(n)
n += 1Try it yourself
- 1
Move the break
In the first example, move the
if n > 10check below theif n % 2 == 0block. Run it. The loop no longer breaks at 12. Work out why: 12 is even, socontinueskips it before the break test is reached. - 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 usebreak. - 3
else or flag?
Rewrite the prime check with a flag variable (
is_prime = True, set it to False beforebreak, test it after the loop). Compare it with the loopelseversion. Which is shorter, and which would a new reader find clearer?
Code & diagrams
Change 12 to 9 and run again: the loop no longer breaks, so every number is handled.
Expected output
Handling 3
8 is even, skip
Handling 5
Too big, stop at 12
Loop finishedChange 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.)
Expected output
Dev is not in the list
29 is prime
21 is divisible by 3Break 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.
total = 0
if total == 0:
breakMyth 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
elseclause 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 bybreak. Because the name is confusing, a short comment such as# no breakis considered good practice. - ▸
For simple searches, Python has better tools than a hand-written loop:
x in items,any(...)andnext((x for x in items if cond), default). Reach for afor/elsewhen the loop needs more than one statement of work per candidate. - ▸
A
returninside a loop (Topic 5.10) is often a cleaner early exit thanbreakplus code after the loop, because it ends the whole function at the moment the answer is known. - ▸
Inside
try/finally(Topic 7.1), abreak,continueorreturnstill runs thefinallyblock 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, sorange(2, math.isqrt(candidate) + 1)is enough (andcandidate < 2must be rejected first, since 0 and 1 are not prime). - ▸
breakandcontinueare 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
breakends 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
continueends only the current iteration. Python jumps straight to the next pass: back to the condition in awhile, or to the next item in afor. Use it to skip items you don't want to process, which keeps the main work un-indented instead of wrapped in a bigif. - 3
Both work on the nearest loop only. In a loop inside a loop,
breakleaves 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 givesSyntaxError: 'break' outside loop. - 4
Loops can have an
elseblock, and its name is confusing. Read it as "no break": theelseblock runs when the loop ended normally (the items ran out or the condition became False), and it is skipped when abreakended the loop. It is not "else if the loop was empty". - 5
The loop
elseis made for the search pattern: loop over the candidates,breakwhen one matches, and put the "nothing matched" code inelse. It replaces a flag variable such asfound = Falsethat 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
Do not overuse these. A loop with several
breaks andcontinues can be harder to follow than one with a clear condition. A good rule: usecontinueto skip uninteresting cases at the top of the block, usebreakfor the one clear exit, and keep the loopelsefor searches where its meaning is obvious (add a short comment such as# no break).
Explain it without notes
What is the difference between break and continue?
When does the else block of a for loop run?
How do you search a list for a value using for/else, and why is that nicer than a flag?
Why can continue cause an infinite loop in a while loop?
Practice
Loop over [12, 25, 49, 50, 56] and print the first number divisible by 7, then stop. Output: First multiple of 7: 49.
Add up the positive numbers in [3, -1, 4, -5, 2], skipping negatives with continue. Print Total: 9.
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.
breakmakes the finished condition obvious and saves work, but a loop with many exits is harder to reason about. Keep it to one clearbreak. - ↔
Loop else vs flag. The loop
elseis 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
breakandcontinuedo and which loop they affect.Done when you can read the loop
elseas "no break".Done when you can write the search pattern and the prime check with for/else.
Done when you can spot the
continuetrap in a while loop.