break and continue
`break` leaves the loop entirely; `continue` skips to the next pass of the loop.
Used in 16 lessons of the course, from 00.06.
Inside a for or while loop, you sometimes want to change the normal flow.
breakends the loop right there. Python carries on with the first line after the loop.continueabandons only the current pass. The loop moves on to the next item.
They almost always sit inside an if: "if this happens, leave" or "if this happens, skip it". That way you avoid nesting the whole loop body inside another if, and the code reads top to bottom.
In the course you'll see continue to ignore empty or uninteresting entries, and break to stop a chat loop when the user types "quit", or once you've found what you were looking for.
Note: they only affect the closest loop that contains them. With nested loops, the outer loop keeps running.
Reach for it when: you want to skip certain items in a loop (`continue`) or stop it early because you're done (`break`).
Examples
Common mistake
for row in [[1, 2], [3, 4]]:
for x in row:
if x == 2:
break
print(x)Why: `break` only leaves the inner loop. The outer loop continues with the next row.
How to write it: Put the loops in a function and use return to leave both, or use a flag variable you check in the outer loop.
Common mistake
for word in ["a", "b", "c"]:
if word == "b":
break
print(word)
print("done")Why: You wanted to skip only "b", but `break` stops the whole loop, so "c" is never printed.
How to write it: Use continue when you want to skip one item and keep going with the rest.
