Python break vs continue
Both are used only inside loops. break ends the loop right there and moves on to the code after the loop. continue skips only the rest of the current iteration and goes on to the next one. The loop keeps going.
break # end the loop
continue # go on to the next iteration
Side by side in the same spot
In a loop that prints 1 to 5, a break at 3 drops 3 and everything after it. A continue at 3 leaves out only 3.
for i in range(1, 6): if i == 3: break print(i, end=" ")print() for i in range(1, 6): if i == 3: continue print(i, end=" ")print()1 2 1 2 4 5
break: stop as soon as you find it
Once you have the answer, there is no need to look at the rest. The loop below stops as soon as it finds the first negative number. It never even looks at the -7 further on.
nums = [4, 9, -2, 5, -7]found = Nonefor x in nums: print("check", x) if x < 0: found = x breakprint("first negative:", found)check 4 check 9 check -2 first negative: -2
continue: skip what doesn't fit
Filter out the values you don't want to handle at the top of the loop. Then the code below doesn't have to be indented deep inside an if.
words = ["tea", "", "milk", "#skip", "juice"]count = 0for w in words: if w == "" or w.startswith("#"): continue count += 1 print(count, w)1 tea 2 milk 3 juice
In nested loops, only the inner one
break and continue affect only the innermost loop that contains them. After a break in the inner loop, the outer loop still goes on to its next iteration.
for a in range(1, 4): for b in range(1, 4): if b == a: break print(a, b) print("row", a, "end")row 1 end 2 1 row 2 end 3 1 3 2 row 3 end
To leave both loops at once, put the loops in a function and return, or set a flag variable and break once more in the outer loop.
for-else: only when the loop ends without break
An else attached to a loop runs only when the loop runs to the end without leaving through break. It lets you say "I looked at everything and found nothing" without a flag variable.
for n in [7, 9]: for d in range(2, n): if n % d == 0: print(n, "=", d, "x", n // d) break else: print(n, "is prime")7 is prime 9 = 3 x 3
Common mistakes
continue before updating the value in a while
i = 0
while i < 5:
if i == 2:
continue
print(i)
i += 1
→ Prints 0 and 1, then never stops (an infinite loop)
continue skips the i += 1 below it too. So i stays at 2 forever. Move i += 1 above the continue, or write for i in range(5):.
Indenting else to match the if
for x in [4, 7, 9]:
if x == 7:
print("found")
break
else:
print("none")
→ none is printed first even though 7 is there
This else belongs to the if, so it runs for every value that isn't 7. To mean "not found anywhere", move the else out to the same depth as the for.
break outside a loop
x = 5
if x > 3:
break
→ SyntaxError: 'break' outside loop
break does not get you out of an if. You can use it only inside a for or a while. To end the program use sys.exit(), and to end a function use return.