Loop Controls (break, continue, pass)
Loops let us repeat code, but sometimes we need more control. What if you want to exit a loop early, skip part of it, or leave space for future logic?
Python provides three helpful keywords: break, continue, and pass.
Let's go through each of them with examples.
1. break: Stop the Loop Immediately
Use break when you want to exit the loop entirely, regardless of how many items remain.
Break Loop
for number in range(1, 10): if number == 5: break print("Number:", number)
- This loop prints numbers from 1 to 9.
- When
number == 5, it hitsbreakand exits the loop. - Output is:
1, 2, 3, 4
2. continue: Skip the Current Step
Use continue when you want to skip one iteration and continue to the next one.
Continue Loop
for number in range(1, 6): if number == 3: continue print("Number:", number)
- This skips
number == 3but keeps looping. - Output is:
1, 2, 4, 5
3. pass: Placeholder That Does Nothing
pass is used when you need a block of code syntactically, but you don’t want to add logic yet.
Pass Loop
for letter in "data": if letter == "t": pass print("Letter:", letter)
- When
letter == "t", the program does nothing and continues to the next iteration. - This serves as a placeholder for future logic.
Summary
| Keyword | What It Does |
|---|---|
break | Exits the loop completely |
continue | Skips to the next iteration |
pass | Does nothing (acts as placeholder) |
Quiz
0 / 1
Which Python keyword would you use to skip the current iteration of a loop?
break
pass
continue
exit
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Run
Generate
Execution Result