Chapter 3: Strings and Loops / Lesson 21

Break & Continue

Controlling Loop Execution

Sometimes you need more control over your loops than just the condition. Python provides two powerful keywords that give you fine-grained control: break and continue.

These keywords allow you to change the normal flow of loop execution, making your code more flexible and efficient. Understanding when and how to use them is essential for writing effective Python programs.

The break Statement

The break statement immediately exits the loop, even if the loop condition is still true. When Python encounters break, it stops the loop and continues with the code after the loop.

This is particularly useful when you need to exit a loop early based on a condition that might occur before the loop naturally completes.

break.py
# Exit loop when a condition is met numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for num in numbers: print(num) if num == 5: print("Found 5, exiting loop!") break # Output: 1, 2, 3, 4, 5, "Found 5, exiting loop!" # The loop stops here, even though more numbers exist # Searching for a value items = ["apple", "banana", "cherry", "date"] target = "cherry" for item in items: if item == target: print(f"Found {target}!") break # No need to check remaining items else: print(f"{target} not found")

The continue Statement

The continue statement skips the rest of the current iteration and jumps to the next iteration of the loop. Unlike break, it doesn't exit the loop - it just skips ahead.

This is perfect for situations where you want to process only certain items in a loop while ignoring others.

continue.py
# Skip even numbers, print only odds for num in range(1, 11): if num % 2 == 0: continue # Skip even numbers print(num) # Output: 1, 3, 5, 7, 9 (only odd numbers) # Skip negative numbers numbers = [5, -2, 8, -1, 3, 0, 10] total = 0 for num in numbers: if num <= 0: continue # Skip non-positive numbers total += num print(f"Added {num}, total: {total}") # Only processes 5, 8, 3, 10

Break vs Continue: Key Differences

Understanding when to use break versus continue is crucial:

🛑 break

• Completely exits the loop

• Continues execution after the loop

• Use when: you found what you're looking for, or a condition requires stopping the entire loop

⏭️ continue

• Skips only the current iteration

• Continues with the next iteration

• Use when: you want to skip certain items but keep processing others

Practical Examples: break

Here are real-world scenarios where break is useful:

break_examples.py
# Example 1: Input validation loop while True: age = input("Enter your age (or 'quit' to exit): ") if age.lower() == "quit": print("Goodbye!") break # Exit the loop if age.isdigit(): print(f"You are {age} years old") break # Valid input, exit loop print("Invalid input. Please try again.") # Example 2: Finding first occurrence users = ["alice", "bob", "charlie", "diana"] target_user = "charlie" for index, user in enumerate(users): if user == target_user: print(f"Found {target_user} at index {index}") break # Stop searching once found else: print(f"{target_user} not found") # Example 3: Breaking on error condition scores = [85, 92, 78, 105, 88] # 105 is invalid for score in scores: if score > 100: print(f"Invalid score detected: {score}. Stopping processing.") break print(f"Processing score: {score}")

Practical Examples: continue

Here are common scenarios where continue is the right choice:

continue_examples.py
# Example 1: Processing only valid data data = [10, 20, None, 30, 0, 40, None, 50] total = 0 count = 0 for value in data: if value is None or value == 0: continue # Skip invalid values total += value count += 1 print(f"Added {value}") print(f"Average: {total / count}") # Example 2: Filtering data during iteration names = ["Alice", "", "Bob", " ", "Charlie", ""] valid_names = [] for name in names: if not name.strip(): # Skip empty or whitespace-only names continue valid_names.append(name) print(f"Valid name: {name}") # Example 3: Skip specific values for i in range(1, 21): if i % 3 == 0: continue # Skip multiples of 3 print(i, end=" ") # Print numbers not divisible by 3

Using break and continue Together

You can use both break and continue in the same loop for complex logic:

combined.py
# Process numbers until we find an invalid one or reach limit numbers = [1, 2, -3, 4, 999, 5, 6] processed = [] for num in numbers: # Skip negative numbers if num < 0: print(f"Skipping negative: {num}") continue # Stop if we find a sentinel value if num == 999: print("Found sentinel value, stopping") break # Process valid number processed.append(num * 2) print(f"Processed: {num} -> {num * 2}") print(f"Final processed list: {processed}")

Break in Nested Loops

When break is used in nested loops, it only breaks out of the innermost loop:

nested_break.py
# break only exits the inner loop for i in range(1, 4): print(f"Outer loop: {i}") for j in range(1, 4): if j == 2: print(f" Breaking inner loop at j={j}") break # Only breaks inner loop print(f" Inner loop: {j}") print("Outer loop continues") # To break out of multiple nested loops, use a flag or restructure found = False for i in range(3): for j in range(3): if i * j == 4: print(f"Found: i={i}, j={j}") found = True break if found: break # Break outer loop too

The else Clause with break

Loops can have an else clause that executes only if the loop completes normally (without break):

else_clause.py
# Search for a value numbers = [2, 4, 6, 8, 10] target = 5 for num in numbers: if num == target: print(f"Found {target}!") break else: # This executes only if break was NOT called print(f"{target} not found in the list") # The else clause is useful for search operations primes = [2, 3, 5, 7, 11] check_num = 4 for prime in primes: if check_num % prime == 0: print(f"{check_num} is divisible by {prime}, not prime") break else: print(f"{check_num} might be prime (or divisible by primes not in list)")

Common Patterns and Best Practices

✅ When to Use break

• Searching for an item (exit once found)

• Input validation (exit on valid input)

• Error conditions (stop processing on error)

• Sentinel values (stop when encountering special value)

✅ When to Use continue

• Filtering invalid data (skip bad values, process good ones)

• Skipping specific values (e.g., skip even numbers)

• Error recovery (skip problematic items, continue with others)

• Performance optimization (skip unnecessary processing)

⚠️ Important Considerations

• Use break and continue sparingly - too many can make code hard to follow

• Consider restructuring loops if you have deeply nested break/continue logic

• The else clause with loops only works if break is NOT used

• break only exits the innermost loop in nested structures

Performance Considerations

Using break and continue can improve performance by avoiding unnecessary iterations:

performance.py
# Without break: processes all items even after finding target numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] target = 3 # With break: stops immediately after finding target for num in numbers: print(f"Checking {num}...") if num == target: print("Found!") break # Saves checking remaining 7 numbers # continue helps skip expensive operations data = [10, 0, 20, 0, 30] for value in data: if value == 0: continue # Skip division by zero and expensive calculation result = 100 / value print(f"Result: {result}")
🎉

Lesson Complete!

Great work! Continue to the next lesson.

main.py
📤 Output
Click "Run" to execute...