Skip to main content

Break and Continue

What if you want to exit out of a loop early or skip the current step?

This is where we would use the break and continue commands.

Break

If you want to stop a loop completely, use break.

Consider the following example:

for i in [1, 2, 3, 4, 5, 6, 7]:
if i == 5:
break
print(i)
Output: 1 2 3 4

When break is executed, the entire loop is stopped.

Continue

If you want to skip just one iteration of the loop, use continue.

Observe the following example:

for i in [1, 2, 3, 4, 5, 6, 7]:
if i == 5:
continue
print(i)
Output: 1 2 3 4 6 7

When continue is executed, the current step is skipped and goes back to the beginning of the loop.