Loop Control Statements in Python
Python provides special statements to control the flow of loops — making them more flexible and powerful:
break– exit the loop entirelycontinue– skip the current iterationelse– run a block after the loop ends, unless the loop was exited withbreak
These can be used in both for loops and while loops.
Example 1: The break Statement
break is used to immediately stop the loop, regardless of the loop condition or sequence.
break_example.py
for num in range(1, 10):
if num == 5:
break
print(num)output.txt
1
2
3
4Explanation:
- The loop starts at
1. - When
num == 5, thebreakstatement exits the loop. - The loop prints only
1to4.
Example 2: The continue Statement
continue is used to skip the rest of the current iteration and go to the next loop cycle.
continue_example.py
for num in range(1, 6):
if num == 3:
continue
print(num)output.txt
1
2
4
5Explanation:
- The loop skips printing
3and continues with4and5.
Example 3: The else Clause With Loops
An else block can be attached to a loop:
- It runs after the loop finishes normally (without
break). - If the loop exits with
break, theelseblock is skipped.
else_for.py
for i in range(1, 4):
print(i)
else:
print("Loop completed without break")output.txt
1
2
3
Loop completed without breakExplanation:
- The loop runs all iterations — so the
elseruns.
Example 4: Using break and else Together
break_else.py
for i in range(1, 6):
if i == 4:
print("Breaking at", i)
break
print(i)
else:
print("Loop finished without break")output.txt
1
2
3
Breaking at 4Explanation:
- The loop exits with
break, so theelseblock is not run.
Example 5: while Loop With break
while_break.py
count = 0
while True:
count += 1
print("Count:", count)
if count == 3:
breakoutput.txt
Count: 1
Count: 2
Count: 3Explanation:
- The loop is infinite (
while True). - The loop is stopped by
breakwhen count reaches3.
Example 6: Skipping Odd Numbers With continue
while_continue.py
i = 0
while i < 6:
i += 1
if i % 2 != 0:
continue
print(i)output.txt
2
4
6Explanation:
- Odd numbers are skipped using
continue. - Even numbers are printed.
When to Use Loop Control Statements
| Statement | Purpose |
|---|---|
break | Stop loop early when a condition is met (exit loop) |
continue | Skip current iteration, continue with next |
else | Run only when loop completes without break (useful for search patterns) |
Summary
break,continue, andelsegive you full control of loop behavior.- They can be used in both
forandwhileloops. - Use
breakto exit early,continueto skip an iteration, andelseto handle post-loop actions.
In the next section, we will explore functions — how to define them, use arguments and return values, and build reusable components in Python programs.