Python tutorials · Part 7 of 8

break, continue and else on Python loops

break stops a loop early, continue skips to the next pass, and a loop's else runs only if the loop wasn't broken. Here's how each works, with examples you can run.

Normally a loop runs until its items run out (for) or its condition turns false (while). Three keywords let you change that from inside the loop body: break, continue and the loop's else clause. A fourth, pass, does nothing at all, and is often confused with the others.

break: stop the loop now

break exits the innermost loop immediately. Code after the loop then runs as normal.

temperatures = [21, 23, 25, 41, 24]

for t in temperatures:
    if t > 40:
        print("Sensor fault:", t)
        break
    print("OK:", t)

print("Finished checking")
OK: 21
OK: 23
OK: 25
Sensor fault: 41
Finished checking

The last reading, 24, is never checked: once break runs, the loop is over. Use break when you've found what you were looking for, or when continuing makes no sense.

It works the same way in a while loop, and it's what makes the while True: pattern possible:

n = 0
while True:
    n += 1
    if n * n > 50:
        break
print(n)
8

continue: skip to the next pass

continue abandons the rest of the current pass and jumps straight to the next item (or back to the condition in a while loop). The loop itself keeps going.

values = [4, -1, 7, 0, -3, 5]
total = 0

for v in values:
    if v <= 0:
        continue      # ignore non-positive values
    total += v

print(total)
16

continue is handy for filtering out cases early so the main logic isn't buried in nested if blocks. But if the skip condition is simple, an if around the work, or a comprehension, can be just as clear.

The continue trap in while loops

In a while loop, make sure continue can't skip the line that moves the loop forward:

i = 0
while i < 5:
    i += 1            # update first, so continue can't skip it
    if i == 3:
        continue
    print(i)
1
2
4
5

If i += 1 came after the continue, the loop would hit i == 3 forever.

else on a loop: "no break happened"

Python lets you attach an else block to a for or while loop. It runs only if the loop finished without hitting break. It's best read as "no break".

The classic use is searching:

def find_first_negative(nums):
    for n in nums:
        if n < 0:
            print("Found", n)
            break
    else:
        print("No negatives")

find_first_negative([3, 8, -2, 5])
find_first_negative([3, 8, 5])
Found -2
No negatives

Without else, you'd need an extra "found" flag variable set inside the loop and checked afterwards. A prime-number check shows the same pattern:

for n in range(2, 12):
    for d in range(2, n):
        if n % d == 0:
            break
    else:
        print(n, end=" ")
print()
2 3 5 7 11 

The inner loop's else runs only when no divisor was found, which means n is prime. Note that the else lines up with the inner for, not with the if.

For a while loop, else runs when the condition becomes false, but not if the loop was left with break.

pass: do nothing

pass is a placeholder for "a statement is required here, but I have nothing to do". It doesn't affect the loop at all:

for n in range(3):
    pass          # TODO: fill in later
print("Loop ran, did nothing")
Loop ran, did nothing

Don't confuse pass with continue: continue skips the rest of the pass, while pass just carries on to the next line.

break in nested loops

break only exits the innermost loop it's in. To stop an outer loop as well, the cleanest option is usually to put the loops in a function and return:

def find_pair(nums, target):
    for i in range(len(nums)):
        for j in range(i + 1, len(nums)):
            if nums[i] + nums[j] == target:
                return nums[i], nums[j]
    return None

print(find_pair([2, 7, 11, 15], 18))
(7, 11)

Alternatives are a flag variable checked by the outer loop, or the for … else pattern, but a function with return is the easiest to read.

Common mistakes

  • Expecting break to leave all nested loops. It leaves only the innermost one.
  • Thinking loop else means "if the loop didn't run". It means "if the loop didn't break". An empty loop runs its else too.
  • Putting continue before the counter update in a while loop, which causes an infinite loop.
  • Using pass where you meant continue.
  • Overusing break and continue. A loop with several of each is hard to follow; often a clearer condition, a function or a comprehension does the job.

Practice

  1. Print numbers from 1 to 10 but stop as soon as you reach a multiple of 7.
  2. Print the numbers from 1 to 10 except multiples of 3.
  3. Using for … else, check whether "x" appears in "python" and print "found" or "not found".

Answers

for n in range(1, 11):
    if n % 7 == 0:
        break
    print(n, end=" ")
print()

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

for ch in "python":
    if ch == "x":
        print("found")
        break
else:
    print("not found")
1 2 3 4 5 6 
1 2 4 5 7 8 10 
not found

Where this shows up in machine learning

Early stopping is a break: once the validation loss hasn't improved for a set number of epochs, training stops instead of running to the final epoch. Data-loading code uses continue to skip corrupt files or rows that fail validation, without crashing the whole run. And search loops over hyperparameters often break once a configuration meets the target score.

First Principles, the SchoolWhool newsletter

One machine learning idea, explained properly, every week.

The intuition, the common mistake, and a five-minute way to try it yourself. Written by Gaurav.