Sub topic 9
break and continue in nested loops
This chapter assumes you can write a basic while loop, update a loop variable, and use break and continue in a single loop. Here you will learn which loop each statement affects when loops sit inside other loops, and how to leave several loops at once.
The rule: the innermost loop only
A nested loop is a loop inside the body of another loop. Both break and continue act only on the loop that directly contains them, which is the innermost one. The outer loop does not know that anything happened.
i = 0
while i < 3:
j = 0
while j < 3:
if j == 1:
break
print(i, j)
j += 1
i += 1This prints 0 0, 1 0 and 2 0. When j reaches 1, break ends the inner loop. Control then moves to i += 1 in the outer body, and the outer loop carries on with the next value of i.
continue in an inner loop
continue skips the rest of the inner body and jumps back to the inner condition. The outer loop is not affected. The warning from the previous chapters still applies. If the inner loop updates its variable at the bottom of the body, continue must not skip that update.
i = 1
while i <= 3:
j = 0
while j < 4:
j += 1
if j == 2:
continue
print(i, j)
i += 1For each i, this prints pairs with j equal to 1, 3 and 4. The update j += 1 comes first, so skipping the print never skips the update.
Leaving both loops
Sometimes you want to stop everything once you find what you are looking for. A plain break is not enough, because it only exits the inner loop. There are three common ways to handle this.
Return from a function
If the loops live in a function, return leaves all loops at once and also hands back a result. This is usually the cleanest option.
def find_pair(nums, target):
i = 0
while i < len(nums):
j = i + 1
while j < len(nums):
if nums[i] + nums[j] == target:
return i, j
j += 1
i += 1
return None
print(find_pair([2, 7, 11, 15], 9))This prints (0, 1). The function returns None if no pair adds up to the target.
Use a flag variable
A flag is a boolean variable that records whether something happened. Set it before break, then check it in the outer loop.
nums = [2, 7, 11, 15]
target = 9
found = False
i = 0
while i < len(nums):
j = i + 1
while j < len(nums):
if nums[i] + nums[j] == target:
found = True
break
j += 1
if found:
break
i += 1
print("found" if found else "not found", i)The inner break ends the inner loop. The if found: check then ends the outer loop. Because the final i += 1 is skipped, i still holds the index of the first number, and the program prints found 0.
Use the loop else clause
The else clause of a loop runs only if no break happened. In a nested loop, you can put it on the inner loop and use it to decide whether the outer loop should continue. This is shorter than a flag, but harder to read at first.
rows = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
wanted = 5
r = 0
while r < len(rows):
c = 0
while c < len(rows[r]):
if rows[r][c] == wanted:
break
c += 1
else:
r += 1
continue
break
print("found at", r, c)This prints found at 1 1. If the inner loop ends without a break, the else block advances r and uses continue to restart the outer loop. If the inner loop did break, the else block is skipped and the final break ends the outer loop.
Choosing a technique
| Technique | Best when | Cost |
|---|---|---|
| `return` | The loops are inside a function and you need a result | Requires moving the code into a function |
| Flag variable | You need to do more work after the loops | An extra variable and an extra check |
| Loop `else` | You want the shortest code and your readers know the idiom | Harder to read |
Common mistakes
- Expecting
breakto stop the outer loop. It stops only the loop it is written in. - Forgetting to reset the inner variable. In the examples,
j = 0sits inside the outer body, so each outer pass starts the inner loop fresh. If you move it outside, the inner loop runs only once. - Putting
continuebefore an update in the inner loop. The result is an infinite loop.
Exercise
In this code, what is printed, and why? i = 0 while i < 3: i += 1 j = 0 while j < 3: j += 1 if j == 2: break print(i, j)
Show answer
It prints "1 1", "2 1" and "3 1". In each outer pass, j becomes 1 and prints. On the next inner pass j becomes 2, and break ends only the inner loop. The outer loop then continues until i reaches 3.