break and continue in Python
break ends a loop early, and continue skips the rest of the current iteration and starts the next. Both work inside for and while loops, and in a nested loop they act on the innermost loop only, so leaving both loops together takes a flag variable or a function.
Key facts
breakleaves the innermost loop at once. The lines after the loop run next.continuejumps to the next iteration. In a while loop, put the counter update before it or the loop never moves on.passdoes nothing. It fills a block that must not be empty.- The inner loop of a nested loop runs all the way through on every iteration of the outer loop.
- An
elseafter a loop runs only when the loop ended without abreak.
What do break and continue do in Python?
break ends the loop it is in, and continue ends only the current iteration. Both are loop control statements that sit inside an if in the loop's block, because on their own they would fire on the first iteration.
for n in [3, 8, 12, 5]:
if n > 10:
break
print(n)
print("Stopped at the first number over 10")3 8 Stopped at the first number over 10
The break runs when n is 12, so 12 and 5 never print and the program moves on after the loop. continue does less, dropping the rest of the current iteration so the loop moves on to the next item.
for n in [3, -1, 8, -4, 5]:
if n < 0:
continue
print(n)3 8 5
What is the difference between break, continue and pass?
break leaves the loop, continue skips to the next iteration, and pass does nothing at all. pass exists because a block can't be empty, so it holds a place for code you haven't written yet.
| Statement | What it does | Use it when |
|---|---|---|
break | Ends the loop immediately | You found what you were looking for |
continue | Skips the rest of this iteration and starts the next | The current item doesn't qualify |
pass | Does nothing | A block has to exist before its code is written |
for n in range(1, 6):
if n == 3:
pass
print(n)1 2 3 4 5
pass changes nothing, so every number prints. Replace it with continue and the 3 disappears. Replace it with break and the loop stops after 2.
How does continue work in a while loop?
continue works the same way in a while loop as in a for loop, with one trap. It jumps straight back to the condition, so a counter update placed after it is skipped and the loop repeats the same iteration forever. Update the counter before the continue.
i = 0
while i < 6:
i = i + 1
if i % 2 == 0:
continue
print(i)1 3 5
The update on the first line of the block runs on every iteration. The continue skips the even numbers, and the odd ones reach the print.
How do nested loops work in Python?
A nested loop is a loop inside another loop. The inner loop runs all the way through on every iteration of the outer loop, so an outer loop of two iterations and an inner loop of three run the inner block six times.
for color in ["red", "blue"]:
for size in ["S", "M", "L"]:
print(color, size)red S red M red L blue S blue M blue L
The outer loop picks a color, the inner loop walks every size for that color, and only then does the outer loop move on. Two levels are common. At three or more, the loop is usually better split up, and a later lesson on functions shows how.
How do I break out of a nested loop in Python?
Set a flag variable, because a break leaves only the loop it sits in. In the inner loop, a break hands control back to the outer loop, which moves on to its next iteration. A flag variable is a boolean that records whether the search succeeded, and the outer loop checks it right after the inner loop and breaks too.
for color in ["red", "blue"]:
for size in ["S", "M", "L"]:
if size == "M":
break
print(color, size)
print("Done")red S blue S Done
Each time the inner loop reaches M, it stops, but the outer loop still goes on to blue. A flag variable can stop both loops at the first pair whose product is 12.
done = False
for a in range(1, 5):
for b in range(1, 5):
if a * b == 12:
print("Found", a, "times", b)
done = True
break
if done:
breakFound 3 times 4
Without the second break, the outer loop would keep going and print Found 4 times 3 as well. Putting the loops inside a function and using return is the other common way out, and functions come later in the course.
What does an else clause do after a loop in Python?
The else clause runs when the loop ends without hitting a break. It is the usual way to report that a search found nothing, because a break means the search succeeded and skips the else.
for n in [4, 9, 15]:
if n > 10:
print("Found", n)
break
else:
print("Nothing over 10")
for n in [4, 9, 5]:
if n > 10:
print("Found", n)
break
else:
print("Nothing over 10")Found 15 Nothing over 10
The else belongs to the for, not to the if, which is why it is indented at the loop's level. The same clause works on a while loop, where it runs once the condition becomes false.
Common mistakes with break and continue in Python
These four mistakes with break and continue are the common ones. Two are errors Python reports at once, and two are loops that behave wrongly without a message.
- SyntaxError: 'break' outside loop.
breakonly works inside a loop. Anifon its own isn't a loop, so there is nothing to leave. - SyntaxError: 'continue' not properly in loop.
continuewas used outside a loop, the same mistake as a straybreak. continueplaced before the counter update. In a while loop the update is skipped, so the loop repeats the same iteration forever. Move the update above thecontinue.- Expecting
breakto leave every loop. It leaves only the loop it is in. Use a flag variable to leave the outer loop as well.
The first program shows the error, and the second runs until the runner stops it after 15 seconds.
age = 20
if age > 18:
break File "main.py", line 3
break
^^^^^
SyntaxError: 'break' outside loopi = 0
while i < 3:
if i == 1:
continue
print(i)
i = i + 10 Stopped after 15 seconds because the program took too long.
Exercise
Complete the loop so it skips every negative number with continue, stops at the first zero with break, and prints the others before it, giving 4, 7 and 2 on separate lines. The starter prints every number.
numbers = [4, -3, 7, 2, 0, 9, -1]
for n in numbers:
print(n)
4 7 2
Show the solution
numbers = [4, -3, 7, 2, 0, 9, -1]
for n in numbers:
if n == 0:
break
if n < 0:
continue
print(n)
Quiz
This quiz has 5 questions. Pick an answer to see why it is right or wrong.
-
1What does this program print?
for n in range(1, 6): if n == 3: break print(n)break ends the loop as soon as n is 3, before the print on that iteration, so only 1 and 2 appear. Skipping the 3 and going on is what continue does.
-
2What does this program print?
for n in range(1, 6): if n == 3: continue print(n)continue skips only the iteration where n is 3, so every other number prints. Stopping at 3 for good is what break does.
-
3Which keyword fills a block that has nothing to do yet, without changing how the loop runs?
pass does nothing at all. continue and break both change how the loop runs, and skip is not a Python keyword.
-
4In a nested loop, which loop does break leave?
break leaves the innermost loop that contains it, and the outer loop moves on with its next iteration. Leaving both needs a flag variable or a function.
-
5What does this program print?
for n in [2, 4, 6]: if n % 2 == 1: break else: print("All even")None of the numbers is odd, so break never runs and the else clause after the loop prints All even. The else belongs to the for, not to the if.