break and continue
- Python course
- Beginner
- Lesson 45/116
- 3 min
Learn to exit with break and skip with continue.
break and continue
break ends the loop entirely. continue skips the current iteration and goes to the next:
for i in range(5):
if i == 3:
break
print(i) # 0 1 2This example ends the loop when i reaches 3. continue just skips that iteration.
break is used in search loops to say 'found it, exit'.
Searching with break
break is mostly used in search loops. When the target is found, exiting the loop saves time:
for n in [1, 3, 5, 7]:
if n == 5:
print("Found")
breakThis prints 'Found' when it hits 5 and exits. Without break, the loop would continue to the end.
Practice Exit with break
Write a for i in range(5): loop. Exit with if i == 3: break. Add print(i).
Starter code
# Loop with breakSample solution
for i in range(5):
if i == 3:
break
print(i)Expected output
0 1 2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does break do?
- Raises an error
- Skips an iteration
- Restarts the loop
- Ends the loop Correct answer
Explanation: break ends the loop entirely.
2 Complete continue
for i in range(5):
if i == 2:
____
print(i)
for i in range(5):
if i == 2:
continue
print(i)
Explanation: continue skips the i=2 iteration.
3 Match the keywords
| Term | Meaning |
|---|---|
break |
Exit the loop |
continue |
Skip an iteration |
pass |
Empty block |
range |
Number range |