Using break and continue

Concepts covered: Loop Control

Python has 2 statements for controlling loop execution: break exits the loop immediately, and continue skips the rest of the current iteration and moves to the next one.

The break Statement

break immediately terminates the innermost loop. Execution continues with the first statement after the loop:

# Find first negative number
numbers = [1, 5, 3, -2, 7, 8]

for num in numbers:
    if num < 0:
        print("Found negative:", num)
        break
    print("Checked:", num)

print("Search complete")

Output:

Checked: 1
Checked: 5
Checked: 3
Found negative: -2
Search complete

When the loop finds -2, break executes and the loop ends immediately. The remaining items (7, 8) are never checked.

The continue Statement

continue skips the rest of the current iteration and jumps to the next iteration of the loop:

# Print only positive numbers
numbers = [1, -2, 3, -4, 5]

for num in numbers:
    if num < 0:
        continue
    print(num)

print("Done")

Output:

1
3
5
Done

When continue executes, the loop immediately moves to the next item. The print statement after continue is skipped for negative numbers.

break vs continue

The 2 statements differ in what happens to the rest of the loop:

break
  • Exits the loop entirely
  • Loop body never runs again
  • Continues after the loop
  • Use for early termination
continue
  • Skips current iteration only
  • Loop continues with next item
  • Loop may run many more times
  • Use to skip certain items

break and continue in while

These statements work the same way in while loops:

# Process until sentinel value
# -1 is the sentinel value
data = [10, 20, -1, 30, 40]
i = 0
total = 0

while i < len(data):
    if data[i] == -1:
        break
    total = total + data[i]
    i = i + 1

print("Total before sentinel:", total)

print("---")

# Skip processing errors
values = [5, 0, 3, 0, 2]
i = 0
results = []

while i < len(values):
    val = values[i]
    i = i + 1
    if val == 0:
        continue
    results.append(10 / val)

print("Results:", results)

Output:

Total before sentinel: 30
---
Results: [2.0, 3.3333333333333335, 5.0]

Combining break with flags

Sometimes you need to know whether a loop exited normally or via break. A flag variable can track this distinction:

# Search with a found flag
numbers = [1, 3, 5, 7, 9, 11]
target = 7
found = False

for num in numbers:
    if num == target:
        found = True
        break

if found:
    print("Found", target, "in the list!")
else:
    print(target, "not found")

# Same search, target not present
target = 8
found = False
for num in numbers:
    if num == target:
        found = True
        break

if found:
    print("Found", target)
else:
    print(target, "not found")

Output:

Found 7 in the list!
8 not found

The flag variable starts False and becomes True only if the target is found. After the loop, you check the flag to determine the outcome. This pattern is useful when you need different behavior based on whether the search succeeded.

Nested loops and break

The break statement only exits the innermost loop. If you've nested loops and want to exit the outer loop, you need additional logic like a flag variable:

# break only exits inner loop
for i in range(3):
    for j in range(3):
        if j == 1:
            break
        print("i =", i, "j =", j)
    print("Outer loop continues, i =", i)

print("---")

# Use a flag for outer loop
found = False
for i in range(3):
    if found:
        break
    for j in range(3):
        print("Checking:", i, j)
        if i == 1 and j == 1:
            found = True
            break

print("Stopped at i=1, j=1")

Output:

i = 0 j = 0
Outer loop continues, i = 0
i = 1 j = 0
Outer loop continues, i = 1
i = 2 j = 0
Outer loop continues, i = 2
---
Checking: 0 0
Checking: 0 1
Checking: 0 2
Checking: 1 0
Checking: 1 1
Stopped at i=1, j=1

These rules keep break and continue from causing subtle bugs and keep loop logic readable:

Do
  • Use break for early exit on first match
  • Use continue to skip invalid items
  • Update counter before continue in while
  • Use flags to exit outer loops
Avoid
  • Use break when you need all matches
  • Nest continue inside complex conditions
  • Forget the counter update, which causes an infinite loop
  • Assume break exits all nested loops

break and continue are most valuable when processing input that has mixed valid and invalid entries. Use continue to skip bad records and break to stop as soon as a target is found.

A common pattern in searching is to use break when a match is found and rely on a flag variable or else clause to detect when no match was found after the full loop completes.

In while loops, forgetting to update the loop counter before a continue statement is a frequent cause of infinite loops. Always ensure the condition can eventually become False regardless of which path through the loop body is taken.

About this lesson

This section is part of the Loops: Beginner lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.