Python break and continue
Core idea
break exits the nearest enclosing loop. continue skips the remaining statements of the current iteration; a for loop advances to its next item and a while loop tests its condition again. Use these statements inside a loop, often under an if condition.
for label in ["A", "STOP", "B"]: if label == "STOP": break print(label)print("Done")STOP exits the loop before printing the marker. B is never visited.
Skip a rejected value
for reading in [3, -1, 6]: if reading < 0: continue print(reading)The negative value is skipped, but iteration resumes with 6.
Advance before continuing
n = 0while n < 4: n = n + 1 if n == 2: continue print(n)The counter advances even when 2 is skipped, so the loop finishes.
Common mistake
In a while loop, a continue before a necessary update can leave the condition true indefinitely. Move the update before the skip, or ensure every branch updates state. Do not execute an unbounded broken loop.
Practice
Visit [5, -2, 4, 0, 8]. Skip negatives, stop at zero, and print all other values visited before stopping.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Break and continue behavior
Check your understanding of break and continue.
What is printed?
for c in "ABC": if c == "B": break print(c)What is printed?
for c in "ABC": if c == "B": continue print(c)What is printed?
n = 0while n < 3: n = n + 1 if n == 2: continue print(n)What should you verify when using continue in a while loop?