Master the use of break and continue to control loop flow, allowing you to exit loops early or skip specific iterations without stopping the entire process.
What it is
In Python, loops (for and while) normally execute their body for every item in a sequence. Two keywords provide fine-grained control over this execution:
break: Immediately terminates the current loop. Execution continues with the first statement after the loop block.continue: Skips the rest of the current iteration and jumps back to the top of the loop to begin the next iteration.
Think of break as "stop everything" and continue as "skip this one, move on."
Why it matters
- Efficiency: Stop searching once a target is found instead of iterating through the entire list.
- Data Filtering: Ignore invalid or unwanted data points during processing without breaking the loop.
- Complex Logic: Handle edge cases within nested structures more cleanly than using multiple boolean flags.
- User Interaction: Exit input validation loops immediately when valid data is received.
Syntax or steps
The syntax is straightforward. Place the keyword inside an if statement within your loop body.
for item in collection:
if condition_to_stop:
break # Exits the loop entirely
if condition_to_skip:
continue # Jumps to next iteration
# Normal processing code goes here
Example
Consider a scenario where we process a list of numbers. We want to ignore negative numbers (using continue) but stop completely if we encounter the number 100 (using break).
numbers = [5, -2, 10, -8, 3, 100, 7]
processed = []
for n in numbers:
if n < 0:
print(f"Skipping negative number: {n}")
continue
if n == 100:
print("Found 100! Stopping loop.")
break
processed.append(n)
print(f"Processed: {n}")
print(f"Final list: {processed}")
Explanation:
- The loop starts with
5. It is not negative and not 100, so it is added toprocessed. - The loop hits
-2. The firstiftriggers.continueskips the rest of the block, so-2is never added toprocessed. - The loop hits
10and3, which are processed normally. - The loop hits
100. The secondiftriggers.breakexits the loop immediately. The number7is never reached.
Common mistakes
- Unreachable Code: Placing statements after
breakorcontinueinside the same block means they will never run. Always ensure logic flows correctly around these keywords. - Breaking Nested Loops: A
breakonly exits the innermost loop. To exit outer loops, you often need a flag variable or a function return. - Overusing Continue: If you find yourself writing complex
if/elseblocks just to avoidcontinue, consider restructuring the logic. Sometimes filtering the list beforehand is cleaner. - Forgetting Indentation: These keywords must be inside the loop's indented block. Placing them outside causes a syntax error or logical failure.
When to use it
Compare these tools with standard conditional logic.
| Scenario | Best Tool | Reason |
|---|---|---|
| Search for a specific item | break | No need to check remaining items once found. |
| Process all items except bad ones | continue | Keeps the loop running while ignoring exceptions. |
| Simple binary choice (do/do not) | if/else | Clearer intent than jumping out of flow. |
| Exit outer loop from inner loop | Function Return | Cleaner than setting flags and breaking twice. |
Practice
Guided Exercise: Write a loop that prints numbers from 1 to 10. Skip printing any number divisible by 3 using continue.
Challenge: Modify the previous exercise to stop the loop entirely if the number exceeds 8 using break.
Hint for Challenge: Check if n > 8 before checking divisibility. Expected output stops at 8.
Quick check
Question: What happens to the current iteration's remaining code if continue is executed?
Answer: The remaining code in the current iteration is skipped, and the loop proceeds to the next iteration.
Summary
break and continue are essential for efficient loop management, allowing early termination and selective skipping respectively. Use them to optimize performance and handle irregular data, but keep logic simple to maintain readability.