Python lesson 18

Break and Continue. Stop or Skip

Two words that let you take control of a loop mid-lap.

Two Escape Hatches

break leaves the loop straight away. No more laps at all. Continue skips the rest of this lap only, and jumps to the next one. Everything after them in the loop body is not run.

for chest in chests:
if chest == "gold":
break # leave the whole loop
if chest == "empty":
continue # skip to the next chest

chests = ["empty", "rock", "gold", "rock"]
for chest in chests:
    if chest == "gold":
        print("Found the gold!")
        break
    print("Opened a", chest)

Where Does It Stop?

for n in [1, 2, 3, 4, 5]:
    if n == 3:
        break
    print(n)

And With Continue?

for n in [1, 2, 3, 4, 5]:
    if n == 3:
        continue
    print(n)

Skip the Empties

Run it. Continue quietly passes over the empty chests.

chests = ["empty", "silver", "empty", "gold"]
for chest in chests:
    if chest == "empty":
        continue
    print("You found", chest)

Stop at the First Big Number

Print each score until you hit one over 100, then stop the loop.

scores = [10, 55, 8, 130, 42]
for score in scores:
    if score > 100:
        print("Too big! Stopping.")
        break
    print("Score:", score)

Odd Numbers Only

Use continue to skip every even number between 1 and 10.

for n in range(1, 11):
    if n % 2 == 0:
        continue
    print(n)

What you can do on CodeIt

Run the example, change one part, and use the result to check your understanding before moving to the next lesson.