How it works
A break does not leave every surrounding loop or return from a function. In nested loops it affects only the innermost loop containing it. Use return inside a function if the whole search is finished and a result should leave the function.
continue is useful for rejecting an item before doing the main work. In a while loop, ensure any state needed for progress is updated even on a continue path.
A loop’s else clause is skipped by break, but not by continue. If iteration otherwise finishes normally, else can still run. This is useful for reporting that a search found no match.
Common mistakes and boundaries
Both statements must occur in a loop within the same function. They are not substitutes for an if/else decision outside a loop.
Keep filtering and stopping rules visible. Too many scattered exits make it difficult to see which items are processed. Avoid printing sensitive records merely to illustrate progress.
Try it yourself
Change the combined example so the target is absent. Then add a loop else message for that case. Place it at the same indentation as for, not alongside the inner if.
Syntax
break
continueExamples
Using break
Exiting a loop early once a condition is met.
numbers = [1, 3, 5, 8, 9, 12]
for num in numbers:
if num % 2 == 0:
print(f"Found first even number: {num}")
break
print(f"{num} is odd")- The first three values are odd. At 8, the success message is printed and break prevents inspection of the remaining numbers.
- Expected output: 1 is odd 3 is odd 5 is odd Found first even number: 8
Using continue
Skipping specific iterations while letting the loop continue.
for num in range(1, 11):
if num % 2 != 0:
continue # skip odd numbers
print(num) # only prints even numbers: 2, 4, 6, 8, 10- Odd numbers reach continue before print. Even numbers reach print, so only five values appear.
- Expected output: 2 4 6 8 10
Combining break and continue
Using both together to filter and stop early within the same loop.
tasks = ["", "draft", "review", "publish"]
for task in tasks:
if not task:
continue
if task == "review":
print("Found the target task!")
break
print(f"Checked: {task}")- Blank entries are ignored, and the target stops the search. This uses ordinary task labels rather than exposing passwords in output.
- Expected output: Checked: draft Found the target task!
Best practices
- Use break to exit a loop as soon as further iteration is pointless, avoiding unnecessary work
- Use continue to skip invalid or irrelevant items without wrapping the rest of the loop body in an if block
- In nested loops, remember break and continue only affect the innermost loop they are directly inside
- Avoid overusing break/continue in ways that make loop logic hard to follow - sometimes restructuring the condition is clearer
Runtime & versions
Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Python language reference