Python • Control Flow

Break & Continue — Use break and continue appropriately

Master the two keywords that let you control exactly how your loops behave.

Code braces with terminal and markup symbols representing Python programming.
Inside this lesson 10 sections 5 questions 6 figures

SECTION 1

Historical Context & Motivation

Loops are one of the most powerful ideas in programming — they let you repeat actions without rewriting the same lines over and over. But what happens when you need to exit a loop early or skip certain iterations? Early programming languages in the 1950s and 1960s offered very limited ways to manage loop behavior, often relying on clunky GOTO statements that jumped to arbitrary lines of code, making programs confusing to read and debug.

1957 • FORTRAN & Early Loops

FORTRAN introduced structured loops with DO statements, but programmers still relied on GOTO for complex control flow.

1968 • Structured Programming Movement

Edsger Dijkstra published 'Go To Statement Considered Harmful,' arguing that programs should use structured control flow like loops and conditionals instead of GOTO.

1972 • C Language Introduces break & continue

The C programming language formalized break and continue as standard keywords for managing loop behavior, replacing messy GOTO patterns.

1991 • Python Adopts break & continue

Guido van Rossum included both keywords in Python from version 1.0, keeping the clean, readable style that Python is known for.

The core question these keywords solve is straightforward: how can you write a loop that doesn't mindlessly run through every iteration when your program logic requires something more nuanced? Sometimes you've already found what you're looking for and need to stop. Other times you need to skip one problematic item and keep going. Python's break and continue statements give you that precise control.

SECTION 2

Core Principles & Definitions

Before diving into code, let's nail down what each keyword actually does and when you should reach for it. Both break and continue are loop control statements — they only work inside for or while loops. Using them outside of a loop will raise a SyntaxError.

1

break — Exit Immediately

When Python encounters break, it immediately terminates the innermost loop and jumps to the first line of code after that loop. No remaining iterations are executed.
2

continue — Skip This Iteration

When Python encounters continue, it skips the rest of the current iteration and jumps back to the top of the loop to start the next iteration.
3

Only Affects the Innermost Loop

If you have nested loops (a loop inside a loop), break and continue only affect the loop they are directly inside — never an outer loop.
4

Usually Paired with a Condition

You almost always place break or continue inside an if statement so the action triggers only when a specific condition is met.
✦

KEY TAKEAWAY

Think of a loop like riding a Ferris wheel. break is the emergency stop button — the ride halts and you get off immediately. continue is like closing your eyes for one rotation — you skip the view for that round, but the wheel keeps turning and you open your eyes on the next go-around.

SECTION 3

Visual Explanation

The following diagram shows how Python's interpreter handles break and continue within a for loop. Notice that break exits the loop entirely, while continue returns to the loop header for the next iteration.

Flow of break vs continue in a for loopfor item in sequence:Execute loop body codeCondition?No → keep goingMore loop body codeNext iteration / EndYes → breakExit loop completelyYes → continueSkip to next
The pink path shows break exiting the loop entirely to code after the loop. The cyan path shows continue jumping back to the loop header to start the next iteration, skipping any remaining code in the current iteration.

In the diagram above, notice the diamond-shaped decision box labeled "Condition?" — this represents the if statement that typically guards your break or continue. When the condition is false, execution flows straight down through the rest of the loop body. When the condition is true, the program takes one of the two colored escape routes. This visual pattern holds true for both for and while loops.

SECTION 4

How break and continue Work Under the Hood

break in Detail

When Python encounters a break statement, it does three things: (1) it stops executing the current iteration's remaining code, (2) it ignores all remaining items in the sequence (for a for loop) or stops checking the condition (for a while loop), and (3) it moves execution to the first statement after the loop. If the loop has an else clause, that else block is skipped when break is triggered.

💡

Python's Loop else Clause

Python has a unique feature: you can attach an else block to a for or while loop. The else block runs only if the loop completes normally (without hitting break). This is handy for search patterns where you want to know if you found something or not.

continue in Detail

The continue statement is gentler than break. It skips the remaining code in the current iteration and returns to the top of the loop. For a for loop, Python fetches the next item from the sequence. For a while loop, Python re-evaluates the condition. The loop itself keeps running — only the current pass is cut short.

Syntax Patterns

Here is the general pattern for using break inside a for loop:

BREAK PATTERN

for item in sequence: if condition: break # more code # execution resumes here after break

The break sends execution to the line after the loop. Any code below break inside the loop body is not executed for that iteration.

CONTINUE PATTERN

for item in sequence: if condition: continue # this code is skipped when condition is True # loop continues with next item

The continue sends execution back to the top of the loop. The remaining body code is skipped only for the current iteration.

SECTION 5

Common Use Cases & Patterns

Knowing the syntax is only half the battle — you also need to recognize when break and continue are the right tool for the job. The diagram below illustrates four common real-world patterns where these keywords shine.

Common Patterns for break & continue🔍 Search & Stop (break)Find the first item matching a condition,then stop searching immediately.Ex: Find a username in a database list🛑 Input Validation (break)Keep asking the user for valid input ina while True loop; break when valid.Ex: Menu selection or password prompt⏭ Skip Bad Data (continue)When processing a list, skip entries thatare invalid or empty without stopping.Ex: Skip blank lines in a file🎯 Filter & Process (continue)Only process items that meet a criteria;use continue to skip the rest early.Ex: Process only even numbers in a list⚠ Code Comparison: continue vs. indented ifWith continue:for n in nums: if n < 0: continue process(n)↑ Flat structure, easy to readWithout continue:for n in nums: if n >= 0: process(n) ↑ Extra nesting as logic grows
The top row shows two common break patterns (search and input validation). The second row shows two continue patterns (skipping bad data and filtering). The bottom comparison shows how continue can keep your code flat and readable.

One important readability benefit of continue is shown in the bottom section of the diagram. When you have many conditions to check before processing an item, using continue to skip invalid cases keeps your main logic at a lower indentation level. This is sometimes called the guard clause pattern — you handle the exceptions first and let the main logic flow naturally below.

⚠

Warning: Infinite Loops with while and continue

Be careful using continue in a while loop. If the variable that controls the loop's condition is updated below the continue statement, the update will be skipped, and the loop may run forever. Always ensure your loop variable is updated before the continue.

SECTION 6

Worked Example — Finding a Prime Number

Let's walk through a realistic example that uses both break and continue. Suppose we want to find the first prime number in a list that is greater than 10. We'll iterate through a list of numbers, skip non-primes with continue, and stop as soon as we find a match using break.

Find the First Prime > 10 in a List

  1. 1

    Step 1 — Set Up the Data

    We define our list of candidate numbers and a helper function to check if a number is prime. numbers = [4, 6, 8, 9, 11, 15, 13, 17]
  2. 2

    Step 2 — Write the Prime-Checking Function

    We create a function is_prime(n) that returns True if n is prime. Inside this function, we use break to exit early once a divisor is found: def is_prime(n): if n < 2: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False # found a divisor return True
  3. 3

    Step 3 — Loop Through Numbers Using continue

    We iterate through the list. If a number is 10 or less, we use continue to skip it immediately — no need to check primality. If the number is greater than 10 but not prime, we also use continue. result = None for num in numbers: if num <= 10: continue # skip numbers 10 or below if not is_prime(num): continue # skip non-primes result = num break # found it, stop searching
  4. 4

    Step 4 — Trace the Execution

    Let's trace each iteration: • 4 → 4 ≤ 10 → continue • 6 → 6 ≤ 10 → continue • 8 → 8 ≤ 10 → continue • 9 → 9 ≤ 10 → continue • 11 → 11 > 10 ✓ → is_prime(11) returns True ✓ → result = 11 → break
  5. 5

    Step 5 — Output the Result

    print(result) # Output: 11 The numbers 13, 15, and 17 were never examined because break exited the loop as soon as 11 was confirmed as a prime greater than 10.
    Result: 11 — the first prime greater than 10 in our list.

SECTION 7

break vs. continue — Strengths & Pitfalls

While both keywords control loop execution, they serve very different purposes and have distinct strengths and pitfalls. The table below compares them side by side so you can quickly decide which one fits your situation.

Featurebreakcontinue
Effect on loopTerminates the entire loopSkips current iteration only
Remaining iterationsAll skippedContinue as normal
Loop else clauseSkipped (else does not run)Not affected (else can still run)
Best use caseFound what you need; searching is doneCurrent item is invalid; move on
Common pitfallPlacing it too early — code below never runsSkipping a loop variable update → infinite loop
Readability tipAdd a comment explaining why you're exitingUse as a guard clause at the top of the loop

Side-by-side comparison of break and continue

✦

KEY TAKEAWAY

Think of looping through a playlist. Using break is like turning off the music entirely when you find the song you wanted. Using continue is like hitting the skip button on a song you don't like — the playlist keeps playing. Choose break when you want to stop the whole process, and continue when you just want to bypass one bad item.

SECTION 8

Connection to Advanced Concepts

Once you're comfortable with break and continue, you'll encounter related ideas in Python and other languages that build on the same concept of controlling execution flow. Understanding these connections will help you write more expressive and efficient code as you advance.

ConceptWhat It DoesRelation to break/continue
passDoes nothing — a placeholder statementUnlike break/continue, pass has no effect on control flow; it just fills a required code block.
Loop elseRuns code only if the loop didn't hit breakDesigned specifically to pair with break for search patterns.
Exception Handlingtry/except blocks catch errorsSometimes replaces continue for skipping problematic items — you catch the error and continue.
Generator Functionsyield pauses and resumes a functionA more advanced form of flow control — you'll encounter break/continue inside generators too.
List ComprehensionsOne-line loops with filteringThe if clause in a comprehension serves a similar role to continue for filtering.

How break and continue relate to advanced Python concepts

As you progress, you'll find that many uses of continue in simple filtering scenarios can be replaced by list comprehensions with if clauses. For example, [x for x in nums if x > 0] accomplishes the same filtering as a loop with continue in a single line. However, break has no direct equivalent in comprehensions, which is why understanding loops with break remains essential.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

Explain in your own words the difference between break and continue. If you have a for loop that iterates over the numbers 1 through 10 and you place a break inside an if num == 5 condition, which numbers get processed?
Show answer
The numbers 1, 2, 3, and 4 would be fully processed. When num reaches 5, the if condition becomes True and break triggers, which terminates the entire loop. The numbers 5 through 10 are never processed. If you used continue instead, only the number 5 would be skipped, and 1–4 plus 6–10 would all be processed. The key distinction: break ends the loop; continue skips just one iteration.

Question 2: BASIC CALCULATION

What is the output of the following code? total = 0 for n in [3, 7, 2, 8, 5, 1]: if n > 6: continue total += n print(total)
Show answer
The output is 11. The loop processes each number, but whenever n > 6 is True (for 7 and 8), continue skips the total += n line. The numbers that actually get added are 3, 2, 5, and 1, giving 3 + 2 + 5 + 1 = 11. The numbers 7 and 8 are skipped but the loop still finishes all six iterations.

Question 3: INTERMEDIATE

Write a program that asks the user to enter numbers one at a time. Use a while True loop. If the user enters a negative number, print 'Skipping negative' and use continue. If the user enters 0, print 'Done!' and use break. Otherwise, add the number to a running total and print it.
Show answer
Here is a correct solution: total = 0 while True: num = int(input('Enter a number: ')) if num < 0: print('Skipping negative') continue if num == 0: print('Done!') break total += num print('Running total:', total) The continue statement prevents negative numbers from being added to the total. The break exits the infinite while True loop when the user enters 0. Notice the order matters: we check for negatives and zero before adding to the total.

Question 4: APPLIED

You are writing a program to search a list of student records (each a dictionary with keys 'name' and 'grade'). Write a loop that finds the first student with a grade of 'A' and prints their name. If no student has an 'A', print 'No A students found.' Use break and the loop else clause.
Show answer
students = [ {'name': 'Alice', 'grade': 'B'}, {'name': 'Bob', 'grade': 'C'}, {'name': 'Carol', 'grade': 'A'}, {'name': 'Dan', 'grade': 'B'}, ] for student in students: if student['grade'] == 'A': print(student['name']) break else: print('No A students found.') This prints 'Carol'. The else clause attached to the for loop only executes if the loop finishes without hitting break. Since Carol has an 'A', break fires and Dan is never checked. If no one had an 'A', the else block would print the 'not found' message.

Question 5: CRITICAL THINKING

Consider this nested loop. What does it print, and why? Explain the role of break in the context of nested loops. for i in range(3): for j in range(3): if j == 1: break print(f'i={i}, j={j}') Bonus: How would you modify this code so that the outer loop also stops when j == 1?
Show answer
The output is: i=0, j=0 i=1, j=0 i=2, j=0 The inner break only affects the inner loop. Each time j reaches 1, the inner loop exits, but the outer loop continues with the next value of i. So for every value of i (0, 1, 2), only j=0 is printed before break fires. To stop the outer loop too, you could use a flag variable: set found = True before the inner break, then check if found: break in the outer loop right after the inner loop finishes. Another approach is to wrap the nested loops in a function and use return to exit both loops at once.

SUMMARY

Lesson Summary

Summary

Python provides two loop control statements for fine-tuning how loops behave. The break statement immediately terminates the innermost loop and skips any remaining iterations, including the loop's else clause. The continue statement skips the rest of the current iteration and jumps back to the loop header for the next cycle. Both keywords are almost always placed inside an if condition to trigger only when needed.

Use break for search-and-stop patterns and input validation loops. Use continue for skipping invalid data and as a guard clause to keep code flat and readable. Remember that both keywords only affect the innermost loop — to break out of nested loops, use a flag variable or wrap the loops in a function.

Varsity Tutors • Python • Break & Continue — Use break and continue appropriately