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.
Code after the loop still runs
break only ends the loop. Python carries on with the first line after it.
for word in ["cat", "dog", "STOP", "bird"]: if word == "STOP": break print(word)print("done")The loop stops at "STOP", then done is printed.
continue — skip this one
for n in [1, 2, 3, 4]: if n == 3: continue print(n)3 hits continue, so its print is skipped. The loop itself keeps going and
prints 4.
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.
look take key
commands = ["look", "take key", "quit", "dance"]# Add a loop that breaks when command equals "quit"; print other commands.Advanced reading
- Loop forever with while True — leave a
while Trueloop withbreak. - Python for else — run code only when a loop finished without
break. - Break out of nested loops — stop an outer loop from inside an inner one.