PYTHON • CONTROL FLOW

Break & Continue — Use break and continue appropriately

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

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.

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.

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.

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.

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.

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.

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.

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
Step 1 — Set Up the DataWe 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
Step 2 — Write the Prime-Checking FunctionWe 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
Step 3 — Loop Through Numbers Using continueWe 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
Step 4 — Trace the ExecutionLet'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
Step 5 — Output the Resultprint(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.

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.

Side-by-side comparison of break and continue
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
✦ 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.

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.

How break and continue relate to advanced Python concepts
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.

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.

Practice Problems

PROBLEM 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?
PROBLEM 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)
PROBLEM 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.
PROBLEM 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.
PROBLEM 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?

Lesson 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