Control flowChapter 47 of 114
Break and Continue
Leave a loop early, or skip the rest of one pass.
break leaves the loop
for n in [1, 2, 3, 4, 5]:
if n == 3:
break
print(n)
print("out")Output
1 2 out
The loop stops the moment break runs. Nothing after it in that pass happens, and there are no more passes.
The usual reason is that you have found what you were looking for:
names = ["Ada", "Grace", "Katherine"]
for name in names:
if name.startswith("G"):
print("first G name:", name)
breakOutput
first G name: Grace
continue skips the rest of this pass
for n in range(6):
if n % 2 == 0:
continue
print(n)Output
1 3 5
continue is a guard clause for loops. It lets you deal with the cases you do not care about and keep the real work unindented:
rows = ["", "ada,36", "# a comment", "grace,45"]
for row in rows:
if not row:
continue
if row.startswith("#"):
continue
name, age = row.split(",")
print(name, age)Output
ada 36 grace 45
Written with nested if statements instead, that body would be two levels deeper and harder to follow.
They only affect the nearest loop
In nested loops, break leaves the inner one only:
for row in range(3):
for col in range(3):
if col == 1:
break
print(row, col)Output
0 0 1 0 2 0
To leave both, the usual options are a flag, a function with return, or the for...else construction:
def find(grid, target):
for r, row in enumerate(grid):
for c, value in enumerate(row):
if value == target:
return r, c
return None
grid = [[1, 2], [3, 4]]
print(find(grid, 4))
print(find(grid, 9))Output
(1, 1) None
Putting the search in a function is usually the clearest of the three, because return leaves everything at once.
break and the else clause
A loop's else runs only if no break happened. That pairing is what makes for...else useful:
def has_factor(n):
for d in range(2, n):
if n % d == 0:
print(n, "divides by", d)
break
else:
print(n, "is prime")
has_factor(9)
has_factor(7)Output
9 divides by 3 7 is prime
continue in a while loop
The trap worth repeating: continue jumps straight back to the condition, so anything that advances the counter must come before it.
n = 0
while n < 5:
n += 1
if n == 3:
continue
print(n)Output
1 2 4 5
Move n += 1 below the continue and the loop never ends.
pass is not the same thing
pass does nothing and carries on with the rest of the body. continue skips the rest of the body:
for n in range(3):
if n == 1:
pass
print(n)Output
0 1 2
for n in range(3):
if n == 1:
continue
print(n)Output
0 2
Test yourself
2 questionsIn nested loops, what does break leave?
Show the answer
The innermost loop only — To leave both, use a flag, or put the search in a function and return.
Why is 'continue' dangerous in a while loop?
Show the answer
It jumps back to the condition, so it can skip the line that advances the counter — Put the increment before the continue and the problem disappears.
Functions
Name a piece of work once and run it whenever you need it.