Lesson 18: Loop Control (break and continue)
Learn how to use break and continue to control loops, skip or exit iterations, combine with conditionals, and apply common looping patterns effectively.
Introduction
You know how to loop through lists with for loops. You know how to repeat until a condition changes with while loops.
But sometimes you need more control. You need to exit a loop early when you find what you're looking for. Or skip certain items without processing them.
This is what break and continue do.
break exits the loop immediately. continue skips to the next iteration.
They give you fine-grained control over loop execution.
Lesson Overview
This section contains a general overview of topics you will learn in this lesson.
- Using break to exit loops early
- Using continue to skip iterations
- When to use each
- Combining with conditionals
- Common patterns
The break Statement
break exits the loop immediately, skipping any remaining iterations.
sheets = ["A-101", "A-102", "S-101", "S-102", "M-101"]
# Find first structural sheet
for sheet in sheets:
if sheet.startswith("S"):
print(f"Found structural sheet: {sheet}")
break # Stop searching
Output:
Found structural sheet: S-101
The loop stops as soon as it finds "S-101". It never checks "S-102" or "M-101".
How break Works
When Python hits break, it exits the loop immediately and continues with the code after the loop.
for i in range(1, 11):
if i == 5:
print("Stopping at 5")
break
print(i)
print("Loop finished")
Output:
1
2
3
4
Stopping at 5
Loop finished
The loop processes 1, 2, 3, 4, then hits the break at 5 and exits.
Architectural Example: Finding a Specific Sheet
sheets = ["A-101", "A-102", "A-201", "A-202", "S-101"]
target = "A-201"
found = False
print(f"Searching for {target}...")
for sheet in sheets:
print(f" Checking {sheet}")
if sheet == target:
print(f" Found it!")
found = True
break
if not found:
print(f"{target} not found")
Output:
Searching for A-201...
Checking A-101
Checking A-102
Checking A-201
Found it!
It stops checking once it finds the target. No need to check the remaining sheets.
break with while Loops
break works with while loops too.
revision = 0
while True: # Infinite loop
revision += 1
print(f"Revision {revision}")
if revision >= 5:
print("Approved")
break # Exit the loop
print("Done")
Output:
Revision 1
Revision 2
Revision 3
Revision 4
Revision 5
Approved
Done
while True creates an infinite loop, but break exits it when the condition is met.
The continue Statement
continue skips the rest of the current iteration and moves to the next one.
room_areas = [450.5, 380.2, 520.8, 410.3, 395.7]
# Process only compliant rooms
for area in room_areas:
if area < 400:
continue # Skip non-compliant rooms
print(f"Processing room: {area}m²")
Output:
Processing room: 450.5m²
Processing room: 520.8m²
Processing room: 410.3m²
The rooms with areas below 400 are skipped. The code after continue doesn't run for those items.
How continue Works
When Python hits continue, it skips the rest of the loop body and goes to the next iteration.
for i in range(1, 11):
if i % 2 == 0: # Skip even numbers
continue
print(i)
Output:
1
3
5
7
9
Even numbers (2, 4, 6, 8, 10) are skipped.
Architectural Example: Processing Issued Sheets Only
sheets = ["A-101", "A-102", "A-201", "A-202"]
issued = ["A-101", "A-201"]
print("Processing issued sheets:")
for sheet in sheets:
if sheet not in issued:
continue # Skip draft sheets
print(f" Exporting {sheet}")
print(f" Sending to contractor")
Output:
Processing issued sheets:
Exporting A-101
Sending to contractor
Exporting A-201
Sending to contractor
Draft sheets (A-102, A-202) are skipped entirely.
break vs continue
break:
- Exits the entire loop
- Use when you found what you're looking for
- Use when a condition means you should stop entirely
continue:
- Skips to the next iteration
- Use when you want to skip certain items
- Use when some items don't need processing
# break - stop at first failure
for area in room_areas:
if area < 400:
print("Found non-compliant room, stopping check")
break
print(f"{area}m²: OK")
# continue - skip failures, check everything
for area in room_areas:
if area < 400:
continue # Skip this one
print(f"{area}m²: OK")
Common Patterns
Pattern 1: Early Exit on Error
sheets = ["A-101", "A-102", "INVALID", "A-201"]
print("Validating sheets:")
for sheet in sheets:
if len(sheet) < 5:
print(f"Error: Invalid sheet number '{sheet}'")
break
print(f" {sheet}: Valid")
print("Validation stopped")
Output:
Validating sheets:
A-101: Valid
A-102: Valid
Error: Invalid sheet number 'INVALID'
Validation stopped
Pattern 2: Skip Invalid Data
room_areas = [450.5, -1, 520.8, 0, 410.3]
print("Valid room areas:")
for area in room_areas:
if area <= 0:
continue # Skip invalid data
print(f" {area}m²")
Output:
Valid room areas:
450.5m²
520.8m²
410.3m²
Pattern 3: Find First Match
floor_names = ["Basement", "Ground", "First", "Second"]
target = "First"
for i, floor in enumerate(floor_names):
if floor == target:
print(f"'{target}' is at index {i}")
break
else:
print(f"'{target}' not found")
Output:
'First' is at index 2
Pattern 4: Process Subset
sheets = ["A-101", "A-102", "S-101", "A-201", "M-101"]
print("Architectural sheets only:")
for sheet in sheets:
if not sheet.startswith("A"):
continue # Skip non-architectural
print(f" {sheet}")
Output:
Architectural sheets only:
A-101
A-102
A-201
Real Architectural Workflows
Example 1: Finding Non-Compliant Rooms
room_data = [
{"name": "Office 1", "area": 420},
{"name": "Office 2", "area": 380},
{"name": "Office 3", "area": 450},
{"name": "Office 4", "area": 395},
]
minimum_area = 400
print("Checking for first non-compliant room:")
for room in room_data:
if room["area"] >= minimum_area:
continue # Skip compliant rooms
# First non-compliant room found
print(f"Found: {room['name']} ({room['area']}m²)")
break
print("Check complete")
Output:
Checking for first non-compliant room:
Found: Office 2 (380m²)
Check complete
Example 2: Export Only Changed Sheets
sheets = ["A-101", "A-102", "A-201", "A-202"]
unchanged = ["A-102", "A-202"]
print("Exporting modified sheets:")
for sheet in sheets:
if sheet in unchanged:
print(f" {sheet}: Skipped (unchanged)")
continue
print(f" {sheet}: Exported")
Output:
Exporting modified sheets:
A-101: Exported
A-102: Skipped (unchanged)
A-201: Exported
A-202: Skipped (unchanged)
Example 3: Stop at Budget Limit
items = [
{"name": "Windows", "cost": 50000},
{"name": "Doors", "cost": 30000},
{"name": "Flooring", "cost": 40000},
{"name": "Lighting", "cost": 25000},
]
budget = 100000
spent = 0
print("Adding items to project:")
for item in items:
if spent + item["cost"] > budget:
print(f"\\nBudget limit reached at {spent}")
print(f"Cannot add: {item['name']}")
break
spent += item["cost"]
print(f" {item['name']}: ${item['cost']} (Total: ${spent})")
print(f"\\nFinal total: ${spent}")
Output:
Adding items to project:
Windows: $50000 (Total: $50000)
Doors: $30000 (Total: $80000)
Budget limit reached at 80000
Cannot add: Flooring
Final total: $80000
The else Clause with Loops
Loops can have an else block that runs if the loop completes without hitting break.
sheets = ["A-101", "A-102", "A-201"]
target = "S-101"
for sheet in sheets:
if sheet == target:
print(f"Found {target}")
break
else:
print(f"{target} not found")
Output:
S-101 not found
If break is hit, the else doesn't run. If the loop completes normally, else runs.
This is useful for search patterns:
# Find first non-compliant room
for area in room_areas:
if area < 400:
print(f"Non-compliant: {area}m²")
break
else:
print("All rooms compliant")
Common Mistakes
Using continue when you mean break
# Wrong - continues checking all rooms
for area in room_areas:
if area < 400:
print("Found non-compliant room")
continue # Keeps looping!
If you want to stop at the first non-compliant room, use break, not continue.
break/continue in wrong place
# Wrong - break is outside the if
for area in room_areas:
if area < 400:
print("Non-compliant")
break # This always breaks on first iteration!
break needs to be inside the condition if you want conditional exit.
Forgetting what continue does
for area in room_areas:
if area < 400:
continue
# This code runs for compliant rooms only
print(f"{area}m²: Processing")
After continue, the code below it doesn't run for that iteration.
When NOT to Use break/continue
Don't use continue when filtering:
# Awkward
compliant = []
for area in room_areas:
if area < 400:
continue
compliant.append(area)
# Clearer
compliant = []
for area in room_areas:
if area >= 400:
compliant.append(area)
The second version is more straightforward.
Don't use break when you can use a condition:
# Awkward
count = 0
for i in range(100):
if count >= 10:
break
count += 1
# Clearer
for i in range(10):
# Just loop 10 times
Use the right tool. If you know the count, use range.
Assignment
<div class="lesson-content__panel" markdown="1">
- Create a new file called
loop_control.py - Find first match with break:
- List:
sheets = ["A-101", "A-102", "S-101", "S-102", "M-101"] - Find and print the first sheet starting with "S"
- Use break to stop searching
- List:
- Skip invalid data with continue:
- List:
areas = [450.5, -1, 520.8, 0, 410.3, -5] - Print only positive areas
- Use continue to skip invalid values
- List:
- Search with else:
- List:
sheets = ["A-101", "A-102", "A-201"] - Search for "A-150"
- Use break if found
- Use else to print "not found"
- List:
- Stop at threshold:
- List:
costs = [5000, 3000, 4000, 2500, 6000] - Budget: 10000
- Add costs until budget exceeded
- Use break when limit reached
- Print total spent
- List:
- Process subset:
- List:
sheets = ["A-101", "A-102", "S-101", "A-201", "M-101"] - Process only sheets starting with "A"
- Use continue to skip others
- Print processed sheets
- List:
- Early exit on error:
- List:
areas = [450, 420, -50, 380] - Check each area
- If any negative, print error and break
- Otherwise print "All valid"
- List:
- Real scenario - Compliance check:
- Rooms:
[{"name": "Office 1", "area": 420}, {"name": "Office 2", "area": 380}, {"name": "Office 3", "area": 450}] - Find first non-compliant room (< 400)
- Print its name and area
- Stop checking after first failure
- Rooms:
</div>
Knowledge Check
The following questions are an opportunity to reflect on key topics in this lesson.
- <a class="knowledge-check-link" href="#the-break-statement">What does break do?</a>
- <a class="knowledge-check-link" href="#the-continue-statement">What does continue do?</a>
- <a class="knowledge-check-link" href="#break-vs-continue">When should you use break vs continue?</a>
- <a class="knowledge-check-link" href="#the-else-clause-with-loops">What does the else clause do with loops?</a>
- <a class="knowledge-check-link" href="#common-mistakes">What happens if break is outside the if block?</a>
Additional Resources
This section contains helpful links to related content. It isn't required, so consider it supplemental.
- Python's break and continue documentation covers loop control in detail
- Real Python's guide to loop control provides additional examples and use cases