Lesson 17 of 4043%
(Progress persistence is disabled until Phase 9)
Python
Beginner
break and continue
Control the flow of your loops.
break and continue
What You’ll Learn
You’ll learn how to stop a loop early or skip specific iterations.
The break Statement
With the break statement we can stop the loop before it has looped through all the items.
fruits = ["apple", "banana", "cherry", "mango"]
for fruit in fruits:
print(fruit)
if fruit == "cherry":
print("Found cherry! Stopping.")
break
Expected Output:
apple
banana
cherry
Found cherry! Stopping.
Notice that “mango” is never printed because the loop was broken.
The continue Statement
With the continue statement we can stop the current iteration of the loop, and continue with the next.
for i in range(5):
if i == 2:
continue # Skip the rest of the code for i=2
print(i)
Expected Output:
0
1
3
4
Notice that 2 is missing.
Summary
break: Exits the entire loop immediately.continue: Exits the current iteration and jumps to the next one.