break and continue
🌍 In real life. You're looking through a stack of exam papers for Rimi's. A blank page? Skip it and go on to the next paper. Found Rimi's paper? Stop looking at once; there's no need to check the rest of the stack.
Those two moves, "skip this one" and "stop now", are continue and break.
The idea in one sentence: continue skips the rest of this lap, and break ends the whole loop at once.
Its words:
continue: jump straight to the next lapbreak: leave the loop; Python carries on below itwhile True:: a loop that would run forever, ended only by abreak
Step by step, for for n in range(1, 6): with if n == 3: continue:
- n is 1, then 2: the
ifis False, so each is printed. - n is 3:
continuejumps to the next lap, so 3 is never printed. - n is 4, then 5: printed as usual.
You almost always put continue and break inside an if.
for n in range(1, 6):
if n == 3:
continue
print(n)A for loop can also walk through values written in square brackets, like [4, 7, 0, 5]. That's a list, and Chapter 8 is all about lists. Here break stops the loop as soon as it reaches 0:
for n in [4, 7, 0, 5]:
if n == 0:
break
print(n)
print("stopped")while True: makes a loop that would run forever, and break is the way out. It's handy when you keep asking until the user types a special word:
while True:
word = input("Say something (or quit): ")
if word == "quit":
break
print("You said", word)
print("Bye!")How Python does it. In a for loop, continue takes the next value; in a while loop, it goes back to check the condition. break leaves only the innermost loop it's in.
What it costs. break can save a lot of work: a search that stops at the first match does fewer laps than one that always walks to the end. If the match is near the front, it finishes almost at once.
Mistakes and edge cases.
- continue before the counter. In a
whileloop, acontinueaboven += 1skips the update, so the loop can run forever. - break outside a loop.
breakon its own givesSyntaxError: 'break' outside loop. - break in a nested loop. It ends only the inner loop; the outer one keeps going.
- Lines after break. Anything after
breakin the same block never runs.
Quiz
What does this print?
for i in range(10): if i == 3: break print(i)What does this print?
for i in range(5): if i % 2 == 0: continue print(i)What does this print?
n = 0 while True: n += 1 if n == 4: break print(n)What does
continuedo?- Skips the rest of this lap and starts the next one
- Stops the whole loop
- Starts the loop again from the very beginning
Which line has a mistake?
x = 5 if x > 3: break print(x)
Coding tasks
Print the numbers from 1 to 10, one per line, but skip every multiple of 3 (3, 6 and 9). Use
continue.Keep asking for whole numbers until the user types
0. Then print the total of all the numbers they typed.Ask for a whole number
n(2 or more). It is prime if no number from 2 ton - 1divides it exactly. Printprimeornot prime.