Using break and continue

Concepts covered: Loop Control

Inside a loop body, 2 statements can change the loop's course. break ends the loop at once: the rest of the body is skipped, no more passes happen, and Python moves to the first line after the loop. continue ends only the current pass: the rest of the body is skipped, and the loop moves to the next item, or in a while loop, back to the condition check.

break: stop searching once found

# 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")
Checked: 1
Checked: 5
Checked: 3
Found negative: -2
Search complete

The list has 6 numbers, and only 4 passes run. The first 3 passes fail the if, print "Checked:", and move on. On the fourth pass -2 passes the if, "Found negative: -2" prints, and break ends the loop before the "Checked:" line runs and before 7 and 8 are ever visited. "Search complete" prints because it sits after the loop at the outer indentation, and break only skips what's inside the loop.

numnum < 0What happens
1Falseprints Checked: 1
5Falseprints Checked: 5
3Falseprints Checked: 3
-2Trueprints Found negative: -2, then break
7, 8never testedloop already ended

continue: skip this one

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

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

print("Done")
1
3
5
Done

All 5 passes happen here. On the passes for -2 and -4, continue jumps straight to the next item, so the print(num) below it never runs for those 2 values. The output is 1, 3, 5 on 3 lines, then "Done". Compare that with break, which would have stopped the whole loop at -2 and printed only 1.

break
  • Ends the entire loop.
  • No further items are visited.
  • Execution continues at the first line after the loop.
  • Use it when the answer is found and the rest is wasted work.
continue
  • Ends only the current pass.
  • The next item is visited as usual.
  • Execution jumps to the top of the loop.
  • Use it to skip items that fail a test while keeping the loop running.

Did the loop find it?

After a loop that uses break, the code following it cannot tell on its own whether the loop stopped early or ran out of items. A flag variable records the answer: set it to False before the loop, set it to True right before the break, and test it afterwards with an if. If the loop finishes without ever reaching the break, the flag is still False.

# 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")
Found 7 in the list!
8 not found

break inside while

while True: is a loop whose condition never fails on its own, so a break inside it is the only way out. The pattern suits loops where the exit test belongs in the middle of the body, after some work has been done on the pass, rather than at the top.

guess = 0
while True:
    guess = guess + 7
    if guess > 30:
        break
print("stopped at", guess)

Output:

stopped at 35

The check guess > 30 fails for 7, 14, 21 and 28, so those passes finish and the loop goes round again. At 35 the check passes, break fires, and the print after the loop shows 35.

continue can skip the progress line in while

In a while loop, continue jumps back to the condition check. If the progress line sits after the continue, the pass skips it, the condition sees the same value again, and the loop never ends. In a for loop this cannot happen, because Python itself moves to the next item.

n = 0
while n < 5:
    if n == 2:
        continue
    print(n)
    n = n + 1
Do
  • Use break the moment a search succeeds, so the remaining items are never visited.
  • Pair break with a flag when code after the loop needs to know whether it fired.
  • Put the progress line before any continue in a while loop.
Avoid
  • Expect lines after a break inside the body to run; they are skipped on that pass.
  • Use continue where wrapping the rest of the body in an if would read better.
  • Rely on the loop variable alone to tell you whether a break happened.

The remainder n % 3 is 0 for multiples of 3. What does this loop print?

for n in range(1, 7):
    if n % 3 == 0:
        continue
    print(n)

The order of lines inside the body decides whether the item that triggers break gets processed. When the if holding break comes before the print, the triggering item ends the loop without being printed. When the print comes first, that item is printed and then the loop ends. Either way, the line after the loop runs once.

Swapping continue for break turns a filter into a stop sign. In a loop that sums only positives, continue drops each negative and keeps adding the rest. A break in that spot ends the sum at the first negative, so every positive after it is lost and the total comes out low with no error to warn you.

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.