break, continue, and the Loop-else Clause
15 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Fine-tune loop execution using break and continue. Python also features a unique else clause on loops that makes search algorithms exceptionally clean.
Exiting early with break
break is a statement that ends the nearest loop at once. The program continues with the first line after that loop.
The break statement halts loop execution immediately and resumes at the statement following the loop.
for n in range(1, 10): if n == 4: break print(n)Example 1 · Retry until connected
for attempt in range(1, 6): print(f"Attempt {attempt}") if attempt == 3: print("Connected") breakAttempt 1 Attempt 2 Attempt 3 Connected
What this code does
- The loop could run 5 times, but
breakends it in round 3. - Attempts 4 and 5 never happen.
The console displays 1, 2, and 3. As soon as n == 4, the loop terminates completely.
Skipping iterations with continue
continue is a statement that skips the rest of the current round and moves on to the next round of the loop.
The continue statement skips the rest of the current iteration and jumps directly to the next cycle.
for num in range(1, 6): if num % 2 == 0: continue print(num)Example 2 · Skip every third order
for order in range(1, 7): if order % 3 == 0: continue print(f"Packing order {order}")Packing order 1 Packing order 2 Packing order 4 Packing order 5
What this code does
- When
order % 3 == 0is True,continuejumps straight to the next round. - Orders 3 and 6 skip the
print, so only 1, 2, 4 and 5 are packed.
Even numbers 2 and 4 are skipped, printing only odd numbers 1, 3, and 5.
Python's unique loop-else clause
Loop else is an else block attached to a for or while loop. It runs only when the loop ends normally, that is, without meeting a break.
A loop can have an else block. The else block executes only if the loop finishes normally without hitting a break.
target = "z"for ch in "Python": if ch == target: print("Found") breakelse: print("Target not found in word")Example 3 · No divisor found
number = 49for d in range(2, 7): if number % d == 0: print(f"{number} is divisible by {d}") breakelse: print(f"{number} has no divisor from 2 to 6")49 has no divisor from 2 to 6
What this code does
49 % dis never 0 for d from 2 to 6, sobreakis never reached.- The loop ends normally, so the
elseblock runs. - Only 7 divides 49, and 7 is outside the range.
Example 4 · Searching a product code
product_code = "KB-4471"search_char = "9"
for ch in product_code: if ch == search_char: print(f"Found {search_char}") breakelse: print(f"{search_char} is not in the code")9 is not in the code
What this code does
- Visits each character of the product code.
- Since '9' is not present, no
breaktriggers. - The
elsebranch runs and prints the not-found message.
Because no character matched target, the loop never hit break. The else block runs, printing 'Target not found in word'.
Next step
Check your understanding
10 quick questions