Python · Stage 4 – Repeating Things · Lesson 26 of 50

break and continue

Stop a loop early or skip only its current iteration.

for number in [1, 2, 3]:
    if number == 2:
        break
    print(number)
Line-by-line explanation
  1. The loop begins with 1.
  2. When number becomes 2, the condition is True.
  3. break ends the loop.
  4. Only 1 is displayed.
for number in [1, 2, 3]:
    if number == 2:
        continue
    print(number)
Line-by-line explanation
  1. The loop visits each number.
  2. For 2, continue skips the print line.
  3. The output contains 1 and 3.

Tiny Practice

Skip the word “bad” and display the others.

Starter template

for word in ["good", "bad", "great"]:
    if word == "bad":
        CHANGE_ME
    print(word)
Line-by-line explanation
  1. The if identifies bad.
  2. The missing instruction should skip only that iteration.
Hint
  1. Use continue.
  2. Keep it indented under if.
  3. Do not use break.
Show Solution
for word in ["good", "bad", "great"]:
    if word == "bad":
        continue
    print(word)
Line-by-line explanation
  1. Good is displayed.
  2. Bad triggers continue and is skipped.
  3. Great is displayed.