Python break and continue
1Python break & continue: overview
break ends a loop immediately, while continue abandons only the current round and jumps ahead to the next one.
Before this lesson: Python for Loops, Python while Loops
2Python break & continue: diagram
3Python break & continue: explained step by step
Most loops run from the first item to the last, or until their condition turns False. break and continue let you change that from inside the body: one ends the loop early, the other jumps ahead to the next round. Used well, they remove awkward nesting. Used carelessly, they make a loop hard to follow, so this lesson also covers when each one fits.
break: stop the whole loop
break means "I have what I need, leave the loop now". The moment it runs, Python jumps to the first line after the loop, and the items you have not reached yet are never visited. That is exactly what you want for a search-and-stop: once you have found the answer, looking at the rest is wasted work.
inbox = ["Newsletter", "Invoice #204", "Lunch?", "Invoice #205"]
for subject in inbox:
if subject.startswith("Invoice"):
print("First invoice:", subject)
break
print("Search finished, subject is still", subject)Notice the last line. A loop variable is not erased when the loop ends, so after a break it still holds the item you stopped on. Only trust that if you know the loop really did stop on a match.
continue: skip this item and carry on
continue means "not this one": the rest of the body is skipped for the current item, and the loop moves straight on to the next item. Nothing is stopped, the loop just does less work for this round.
entries = ["42", "n/a", "17", "", "8"]
total = 0
for text in entries:
if not text.isdigit():
continue
total += int(text)
print("Total:", total)Putting the rejection first and then calling continue keeps the normal case at a single level of indentation. The alternative is to wrap the whole body in if text.isdigit():, which works but pushes the real work further to the right with every extra rule you add.
Which one do I need?
Ask yourself: if this item is bad or uninteresting, should the remaining items still be processed? If yes, use continue. If the answer is "no, we are done", use break. Mixing the two up is the most common slip, and it rarely produces an error message, only a wrong result.
In while loops
Both keywords work in while loops, with one twist. continue jumps back to the condition check, so everything after it in the body is skipped, including the line that moves the loop toward its end. If that line sits after the continue, the loop can get stuck:
# Do not run this: it never ends
n = 0
while n < 5:
if n == 2:
continue # n is still 2, so the check passes again, forever
print(n)
n += 1
It prints 0 and 1, then spins silently, because n stays at 2. The rule: do the update before any continue, or take items from a queue so that every round moves forward on its own.
while True: combined with break is the usual way to work through a queue of unknown length. The loop looks endless, but each exit is spelled out inside it:
jobs = ["resize logo", "", "send email", "STOP", "backup db"]
while True:
if not jobs:
print("Queue empty")
break
job = jobs.pop(0)
if job == "":
continue
if job == "STOP":
print("Stop signal received,", len(jobs), "job(s) left")
break
print("Running:", job)Here pop(0) removes the first job, so every round makes progress and the continue on a blank entry is safe.
break only leaves the innermost loop
When one loop sits inside another, break ends only the loop it is written in. The outer loop carries on with its next item.
teams = [["Asha", "Ben"], ["Chen", "Dina", "Eli"], ["Fay"]]
for team in teams:
for member in team:
if member == "Dina":
print("Found Dina, leaving the inner loop")
break
print("Checked", member)
print("Done with team")Eli is never checked, but the outer loop still visits Fay's team. If you want to stop everything once something is found, you need to tell the outer loop too.
A flag variable as an alternative
A flag is a variable, usually True or False, that records whether something happened. Set it right before the inner break, then check it in the outer loop and break there as well. A flag is also handy in a single loop when you need to know afterwards whether the search succeeded.
teams = [["Asha", "Ben"], ["Chen", "Dina", "Eli"], ["Fay"]]
found = False
for team in teams:
for member in team:
print("Checking", member)
if member == "Dina":
found = True
break
if found:
break
print("Found Dina:", found)A last word of advice: one or two break or continue lines in a loop read well. If you need several, step back and see whether the loop can be simplified.
Quick reference: Python break & continue
- Python break vs continue vs pass: Differences — `break` stops the whole loop, `continue` skips the rest of the current iteration and moves to the next one, a…
4Python break & continue: syntax
for item in items:
if skip_this_one:
continue # jump to the next item
if we_are_done:
break # leave the loop right now
... # normal work
while True:
...
if finished:
break # the only way out
5Python break & continue: run the example
Press Run (or Ctrl + Enter). The output (step 6) appears directly below the code. Change anything and run it again.
purchases = [25, -5, 40, 0, 120, 15, 60]
total = 0
for amount in purchases:
if amount <= 0:
print("Skipping invalid amount:", amount)
continue
if total + amount > 150:
print("Budget reached before", amount)
break
total += amount
print("Total spent:", total)Expected outputSkipping invalid amount: -5
Skipping invalid amount: 0
Budget reached before 120
Total spent: 65
7Python break & continue: how the example works
Hover or tap a step to highlight its lines in the example above.
- Line 1-2A list of purchases and a running
totalthat starts at 0 before the loop. - Line 3The loop hands over one amount per round: 25, -5, 40, 0, 120 and so on.
- Line 4-6For -5 and for 0 the amount is not a real purchase. A message is printed and
continueskips lines 7-10, so the loop moves straight to the next item. - Line 7-9Before adding an amount, the code checks whether it would push the total past 150. When 120 arrives, 65 + 120 is 185, so the message is printed and
breakends the loop. The 15 and the 60 are never looked at. - Line 10Only valid amounts that fit the budget get here: 25 and 40, which makes
total65. - Line 11This line is not indented, so it runs once after the loop, whether the loop ended by
breakor by running out of items.
8Python break & continue: common mistakes
Using break when you meant continue
✗ Wrong
scores = [80, -1, 90, 70]
total = 0
for s in scores:
if s < 0:
break
total += s
print(total)✓ Right
scores = [80, -1, 90, 70]
total = 0
for s in scores:
if s < 0:
continue
total += s
print(total)break ends the whole loop, but you only wanted to ignore one bad value. continue skips just that item and keeps going.
Expecting break to leave both loops
✗ Wrong
rows = [["Ana", "Ben"], ["Cy", "Ben"]]
for row in rows:
for name in row:
if name == "Ben":
print("Found Ben")
break✓ Right
rows = [["Ana", "Ben"], ["Cy", "Ben"]]
found = False
for row in rows:
for name in row:
if name == "Ben":
print("Found Ben")
found = True
break
if found:
breakbreak affects only the loop it is written in. Record the result in a flag, then check the flag in the outer loop and break there too.
continue before the counter update in a while loop
✗ Wrong
n = 0
while n < 5:
if n == 2:
continue
print(n)
n += 1✓ Right
for n in range(5):
if n == 2:
continue
print(n)When n is 2, continue jumps back to the condition before n += 1 can run, so n stays 2 forever. A for loop moves to the next number by itself. If you need a while loop, do the update before the continue.
Using break outside of a loop
✗ Wrong
balance = -20
if balance < 0:
print("Overdrawn")
break✓ Right
balances = [50, -20, 10]
for balance in balances:
if balance < 0:
print("Overdrawn")
breakbreak and continue only make sense inside a for or while loop. An if on its own has nothing to leave. Put the check inside a loop, or just remove the break.
9Python break & continue: exercises
Write your answer, then press Check. The checks run in your browser.
1. Find the first failing score
Write code Easy ✓ Completedscores lists test results in the order they were marked. Find the first score below 50 and store it in first_fail. Stop searching as soon as you find it, then print First fail: <score>. With the starting data the output is First fail: 45.
scores = [88, 92, 45, 70, 30]
first_fail = None
# loop over scores and stop at the first one below 50
scores = [88, 92, 45, 70, 30]
first_fail = None
for score in scores:
if score < 50:
first_fail = score
break
print("First fail:", first_fail)
2. Predict the while True loop
Predict the output Medium ✓ CompletedRead the code and type exactly what it will print. Then press Check to run it and compare.
count = 0
while True:
count += 1
if count % 2 == 0:
continue
if count > 7:
break
print("count =", count)
print("stopped at", count)count = 1
count = 3
count = 5
count = 7
stopped at 9
2 more exercises → 5 more examples
Questions learners ask
What is the difference between break and continue in Python?
break ends the whole loop and continues with the code after it. continue only abandons the current round: Python skips the rest of the body and starts the next iteration, or re-checks the condition in a while loop.
Does break stop all the loops when they are nested?
No. break only leaves the innermost loop that contains it. To stop an outer loop as well, set a flag variable before the break and check it in the outer loop, or move the loops into a function and return from it.
Is it bad style to use break and continue?
No, they are normal tools. A single break for search-and-stop or a continue that skips invalid items often reads better than extra nesting. They become a problem only when a loop has so many exits that you can no longer see when it stops.
Further reading
10Next lesson
Up nextPython else on LoopsThe else block of a for or while loop runs once when the loop finishes normally, and is skipped when a break ends the l…Related:
Python pass StatementPython else on LoopsPython Nested Loops
← Python range() Function · All Control Flow lessons · Practise in the IDE