Back to Python Notes
Topic #221

Break and Continue

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:

  1. The loop starts with 5. It is not negative and not 100, so it is added to processed.
  2. The loop hits -2. The first if triggers. continue skips the rest of the block, so -2 is never added to processed.
  3. The loop hits 10 and 3, which are processed normally.
  4. The loop hits 100. The second if triggers. break exits the loop immediately. The number 7 is never reached.

Common mistakes

  • Unreachable Code: Placing statements after break or continue inside the same block means they will never run. Always ensure logic flows correctly around these keywords.
  • Breaking Nested Loops: A break only 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/else blocks just to avoid continue, 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.

ScenarioBest ToolReason
Search for a specific itembreakNo need to check remaining items once found.
Process all items except bad onescontinueKeeps the loop running while ignoring exceptions.
Simple binary choice (do/do not)if/elseClearer intent than jumping out of flow.
Exit outer loop from inner loopFunction ReturnCleaner 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.

Want to go beyond the notes?

Join Coding Now Tech Institute's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Break and Continue – FAQs

Quick answers about learning Break and Continue in Python.

This free note from Coding Now Tech Institute explains Break and Continue in Python — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Python topic on Coding Now Tech Institute, including Break and Continue, is 100% free with no signup required.
With focused practice, most students grasp Break and Continue in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now