Python Loops · Lesson 36 of 149

Python Break, Continue and Loop Else

What you will learn

  • How break leaves a loop at once
  • How continue skips the rest of one pass
  • What else on a loop means, and the "search" pattern it was made for
  • How to leave nested loops with a flag or a function
  • The common mistakes

1. break: leave the loop now

break ends the innermost loop immediately. Python carries on with the first line after the loop:

for n in range(1, 10):
    if n == 4:
        break
    print(n, end=" ")
print("| stopped at", n)
1 2 3 | stopped at 4

The loop would have counted to 9, but at n == 4 it was cut short. break works in both for and while loops, and it is nearly always inside an if.

It is the natural partner of while True (lesson 6.1): the loop runs "forever", and the break is the exit:

n = 0
while True:
    n += 1
    if n == 3:
        break
print(n)
3
Quick check: after `break`, does the rest of the block run?

No. Python leaves the loop at once, and the lines below break in that pass are skipped.

2. continue: skip to the next pass

continue ends only the current pass and jumps to the next one. The loop itself carries on:

for n in range(1, 8):
    if n % 2 == 0:
        continue
    print(n, end=" ")
print()
1 3 5 7 

For every even number, continue skipped the print, so only the odd numbers were shown. In a while loop, continue goes back to the test. Make sure the update has already happened, or the loop may never end:

i = 0
while i < 5:
    i += 1
    if i == 2:
        continue
    if i == 4:
        break
    print("i =", i)
print("end i =", i)
i = 1
i = 3
end i = 4

The update i += 1 came before the continue. Had it come after, i would have stayed at 2 forever.

break or continue?

Statement Effect Think of it as
break ends the loop "I have what I need, stop"
continue ends this pass only "skip this one, go on"

A common use of continue is to filter out unwanted items at the top of the block, which keeps the real work un-nested:

words = ["apple", "", "kiwi", "STOP", "fig"]
for w in words:
    if w == "":
        continue
    if w == "STOP":
        break
    print(w)
apple
kiwi

The empty text was skipped, and the loop ended at STOP, so fig was never reached.

3. else on a loop

Loops may have an else block. It is easy to misunderstand, so remember this rule:

The else block runs when the loop finished normally, that is, without hitting break.

for n in range(2, 6):
    if n == 9:
        break
else:
    print("no break: the loop finished normally")

for n in range(2, 6):
    if n == 4:
        print("found", n)
        break
else:
    print("not found")
no break: the loop finished normally
found 4

In the first loop the break never happens, so the else runs. In the second, break happens at 4, so the else is skipped.

It works the same for while. Note also that an empty loop (no passes at all) counts as finishing normally, so its else runs.

The search pattern

for ... else is made for searching: "look through the items; if I find one, stop; if I get to the end without finding, do something else":

def is_prime(n):
    if n < 2:
        return False
    for d in range(2, int(n ** 0.5) + 1):
        if n % d == 0:
            break
    else:
        return True
    return False

print([n for n in range(2, 30) if is_prime(n)])
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

If a divisor d is found, break leaves the loop and the function returns False. If no divisor is found, the loop ends normally, the else runs, and the number is prime. (def and return are chapter 11; n ** 0.5 is the square root, since a divisor of n never needs to be bigger than that.)

Many programmers find else on a loop confusing and use a flag or a function with return instead. Both styles are fine; know the meaning when you read it.

4. Leaving several loops

break leaves only the innermost loop:

for i in range(3):
    for j in range(3):
        if j == 1:
            break
        print(i, j, end="; ")
print()
0 0; 1 0; 2 0; 

The inner loop stopped at j == 1 each time, but the outer loop carried on. To leave both, use a flag:

found = False
for i in range(3):
    for j in range(3):
        if i * j == 2:
            found = True
            break
    if found:
        break
print(i, j, found)
1 2 True

The inner break sets the flag, and the outer loop checks it and breaks too. A neater way is to put the loops in a function and use return, which leaves everything at once (chapter 11):

def find(items, target):
    for i, v in enumerate(items):
        if v == target:
            return i
    return -1

print(find(["a", "b", "c"], "b"), find(["a"], "z"))
1 -1

(enumerate is lesson 6.6.)

Worked example: stop at the first negative balance

A list of daily balance changes is processed. Skip days with no change (0). Stop and report if the running balance goes below zero.

changes = [50, 0, -30, 0, -40, 20]
balance = 0
for day, change in enumerate(changes, 1):
    if change == 0:
        continue
    balance += change
    if balance < 0:
        print(f"balance below zero on day {day}: {balance}")
        break
else:
    print("balance stayed at or above zero:", balance)
balance below zero on day 5: -20
Day Change Action Balance
1 50 add 50
2 0 continue (skipped) 50
3 -30 add 20
4 0 continue 20
5 -40 add, below zero, break -20

Because break happened, the else did not run. With changes = [50, -30] the loop would end normally and print the else message. The numbers are made up.

Common mistakes

  • Using continue in a while loop before the update, which makes an infinite loop.
  • Thinking break leaves all the loops. It leaves only the innermost.
  • Reading else as "if the loop did not run". It means "if there was no break".
  • Putting break or continue outside a loop, which is a SyntaxError.
  • Using else when a flag would be clearer for readers who do not know the rule.

Key takeaways

  • break ends the innermost loop; continue ends only the current pass.
  • while True: plus break is the standard "repeat until I say stop" loop.
  • A loop's else runs only if the loop was not ended by break; it fits "search, and report if not found".
  • To leave nested loops, use a flag or put the loops in a function and return.
  • In a while loop, do the update before any continue.

Practice

1. What does this print: for n in range(5): with if n == 3: break and then print(n)?

Show answer

0, 1 and 2, each on its own line. At 3, the break ends the loop before the print.

2. Print only the numbers from 1 to 10 that are not divisible by 3, using continue.

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

3. When does the else of a for loop run?

Show answer

When the loop ends normally, without being stopped by break. It also runs for an empty collection.

4. Write a for ... else that prints found if "x" is in a list items, and missing if it is not.

Show answer
for item in items:
    if item == "x":
        print("found")
        break
else:
    print("missing")

5. Why is this loop infinite? i = 0, while i < 5:, if i == 2: continue, then i += 1.

Show answer

When i is 2, continue jumps back to the test before i += 1 runs, so i stays 2 forever. Put the update before the continue.

6. How can you leave two nested loops at once?

Show answer

Set a flag in the inner loop and break from the outer loop when the flag is set, or put the loops in a function and return.