Loops in Python

Module 3 · Loops in Python · Lesson 4 of 6

break and continue

Sometimes you don't want a loop to simply run to its natural end. Two keywords let you steer it from the inside: break and continue. Both work in while and for loops alike.

Stop at 3 — two different ways
if n == 3: break
12345
leaves the loop entirely — 4 and 5 never run.
if n == 3: continue
12345
skips just this round — 3 is jumped, then it carries on.

break leaves the loop entirely — the moment Python hits it, the loop is over and execution jumps to whatever comes after. It's how you stop early: as soon as you've found what you were looking for, break out.

Run it yourselfruns in your browser · Python
main.py

continue is gentler: it skips the rest of the current round and jumps straight back to the top for the next one. The loop carries on — you've just chosen to ignore this particular item.

Run it yourselfruns in your browser · Python
main.py

A nice detail to remember: a break skips a loop's else clause (the loop didn't finish naturally), whereas continue doesn't — it's still the same loop, just moving on.