Break and Continue

► Overview

Break and continue are control statements that modify loop behavior. Break exits the loop immediately, while continue skips the current iteration and moves to the next one. These give you fine control over loop execution.

► Real-World Analogy

Think of searching for your keys:
» break: Found keys! Stop searching immediately
» continue: This drawer is empty, skip to next drawer without stopping search

► Key Concepts

✓ break: Exits the loop completely
✓ continue: Skips current iteration, continues with next
✓ Works with both for and while loops
✓ Useful for early termination or filtering
✓ Can improve efficiency by avoiding unnecessary iterations

■ Break and Continue Examples

/code

Using break – exit when found

for num in range(1, 10):
if num == 5:
print(“Found 5! Stopping…”)
break
print(num)

Using continue – skip even numbers

for num in range(10):
if num % 2 == 0:
continue # Skip even numbers
print(num)

Combined example

for i in range(20):
if i > 15:
break # Stop at 15
if i % 3 == 0:
continue # Skip multiples of 3
print(i)

Output:
1
2
3
4
Found 5! Stopping…
1
3
5
7
9
1
2
4
5
7
8
10
11
13
14

► Important Points

✓ break saves time by exiting when condition is met
✓ continue is useful for filtering unwanted iterations
✓ Don’t overuse – can make code harder to read
✓ Both work in nested loops (affects only current loop)
✓ Can combine with if statements for conditional control

► Remember

✓ break = stop the entire loop
✓ continue = skip to next iteration
✓ Use break for search operations
✓ Use continue for filtering
✓ Consider readability when using these statements

■ Practice Challenge

  1. Write a loop that stops when it finds the first negative number
  2. Print only odd numbers from 1 to 50 using continue
  3. Create a password validator that breaks on first valid entry