Break and Continue
Break and Continue
Sometimes a loop needs extra control.
You may want to stop the loop early, or skip one turn and continue with the next turn.
Python gives us two useful keywords for this:
breakcontinue
What Is Break?
break stops the loop immediately.
Python leaves the loop and moves to the next line after it.
for number in range(1, 6):
if number == 4:
break
print(number)
Output
1
2
3
The loop stops when the number becomes 4.
What Is Continue?
continue skips the current turn.
The loop does not stop. It moves to the next turn.
for number in range(1, 6):
if number == 3:
continue
print(number)
Output
1
2
4
5
The number 3 is skipped.
How They Are Different
breakends the whole loopcontinueskips one turn only
Break in a While Loop
count = 1
while True:
print(count)
if count == 3:
break
count += 1
Continue in a While Loop
count = 0
while count < 5:
count += 1
if count == 2:
continue
print(count)
Code Along
for letter in "Python":
if letter == "h":
break
print(letter)
Mini Challenge
Build a skip number program.
Steps:
- Use a loop to print numbers from
1to5 - Skip number
3 - Print all other numbers
Real World Use Case
Programs use break to stop searches when something is found, and continue to skip invalid data and keep working.
Quiz
- What does
breakdo? - What does
continuedo? - Does
continuestop the loop? - Which one ends the whole loop?
Assignment
Create a program that prints numbers from 1 to 10 but stops when it reaches 6.
Summary
You learned how break stops a loop and how continue skips one turn and keeps the loop running.