Loop Control
Sometimes you need to exit a loop early or skip an iteration. Python provides `break`, `continue`, and `pass` statements to control loop execution.
break
Immediately exits the innermost loop.
for i in range(10):
if i == 5:
break
print(i) # prints 0,1,2,3,4
continue
Skips the rest of the current iteration and moves to the next one.
for i in range(5):
if i == 2:
continue
print(i) # prints 0,1,3,4
pass
A placeholder that does nothing. Useful when syntax requires a statement but you don't want to do anything (e.g., in empty functions or loops).
for i in range(3):
pass # do nothing (yet)
else with loops
Python allows an `else` clause after a loop. It executes only if the loop completes normally (no `break`).
for i in range(5):
if i == 3:
break
print(i)
else:
print("Loop completed without break")
# else block won't run because break occurred
Two Minute Drill
- `break` exits the loop entirely.
- `continue` skips the rest of the current iteration.
- `pass` does nothing; used as a placeholder.
- An `else` after a loop runs only if no `break` occurred.
- Use these to control loop flow precisely.
Need more clarification?
Drop us an email at career@quipoinfotech.com
