break and continue
Leaving a loop early, or skipping one round.
4 minute read
Big idea
break ends a loop immediately. continue skips the rest of this round and goes on to the next one.
break: stop now
for n in range(20, 40):
if n % 7 == 0:
print("Found", n)
break
print(n, "no")output
20 no
Found 21Run and edit it in the app.
Once break runs, the loop is over — even though range had 18 more numbers to go.
break is handy with while True: a loop that would run forever, with the exit in the middle.
while True:
word = input()
if word == "stop":
break
print("You said", word)
print("Bye!")input
hello
python
stop
ignoredoutput
You said hello
You said python
Bye!Run and edit it in the app.
Watch it
continue: skip this one
for n in range(1, 8):
if n % 3 == 0:
continue
print(n)What does it print? Show the answer
1
2
4
5
7Run and edit it in the app.
3 and 6 hit continue, so their print is skipped — but the loop carries on.
else on a loop
A loop can have an else block. It runs only if the loop finished without a break — a neat way to say "searched everything, didn't find it":
n = 29
for d in range(2, n):
if n % d == 0:
print(n, "is not prime")
break
else:
print(n, "is prime")output
29 is primeRun and edit it in the app.
pass: do nothing
A block can't be empty. pass is a placeholder that does nothing — useful while you're still writing:
for n in range(10):
pass # TODO
for n in range(1, 10):
if n % 2 == 0:
break
print(n)output
1
3
5
7
9Run and edit it in the app.
Inside a for loop, which statement skips to the next item without ending the loop?
Think of it like
Flicking through a stack of photos. continue: "blurry — next one". break: "that's the one — stop looking".
Key terms
- break — Ends the loop immediately.
- continue — Skips to the next round of the loop.
- pass — A statement that does nothing.
Check yourself
What does break do?
When does a loop's else block run?
What does pass do?