break and continue
break stops a loop immediately. continue skips the rest of this turn and
moves on to the next one. Both let a loop react to what it finds.
break — stop early
for word in ["cat", "dog", "STOP", "bird"]:
if word == "STOP":
break
print(word)
"bird" is never printed. As soon as break runs, the loop is over and
Python carries on with the code after it.
Inside a function, break ends the nearest enclosing loop and continues after it. return ends the entire function call. Use break when work after the loop still needs to run.
continue — skip this one
for n in [1, 2, 3, 4, 5, 6]:
if n % 2 == 1:
continue
print(n)
Odd numbers hit continue, so their print is skipped. The loop itself keeps
going.
break in a while loop
break works in a while loop too, and is the usual way
to leave a loop whose condition is always true:
counter = 0
while True:
counter = counter + 1
if counter * counter > 50:
break
print(counter)
8 * 8 is the first square over 50, so the loop stops with counter at 8.
See also: For loops, While loops.
Your turn: stop at a sentinel
Print each command until you reach "quit". Do not print "quit" or
anything after it.
commands = ["look", "take key", "quit", "dance"]
# Add a loop that breaks when command equals "quit"; print other commands.
Expected output
look
take key
This practice focuses on what break does. The Memory Game will combine it
with indexing, comparison and scoring.
Practise this in the free Python course, where every exercise checks your code instantly.