Break and Continue in Python
Sometimes you need more control inside loops. The break and continue statements help you change how a loop runs.
Why Break and Continue?
Normally, loops run until their condition becomes False or until all items are processed.
But what if you want to:
- Stop the loop early? ๐ Use break
- Skip to the next iteration without stopping the whole loop? ๐ Use continue
1. Break Statement
break immediately ends the loop, even if the condition is still True.
for i in range(1, 10):
if i == 5:
break # loop stops when i == 5
print(i)
Output: 1 2 3 4
The loop stops when i becomes 5.
2. Continue Statement
continue skips the current iteration and jumps to the next one.
for i in range(1, 10):
if i == 5:
continue # skips printing when i == 5
print(i)
Output: 1 2 3 4 6 7 8 9
The number 5 is skipped, but the loop continues for the remaining numbers.
3. Break and Continue in While Loops
i = 0
while i < 10:
i += 1
if i == 3:
continue # skip when i == 3
if i == 7:
break # stop when i == 7
print(i)
Output: 1 2 4 5 6
Common Mistakes
-
Indentation Errors:
Forgetting to indent
breakorcontinueproperly inside the loop block. -
Using Break Outside a Loop:
break # ❌ SyntaxError: 'break' outside loop -
Using Continue Outside a Loop:
continue # ❌ SyntaxError: 'continue' not properly in loop -
Infinite Loops:
Using
continuewithout updating variables in awhileloop can cause infinite loops.
๐ก Practice Challenges
- Write a loop that prints numbers from 1 to 20 but stops if the number is 13.
- Write a loop that prints numbers from 1 to 10 but skips multiples of 3.
- Ask the user to keep entering numbers, but stop the loop if the user enters 0.
- Print all even numbers between 1 and 50, skipping the odd numbers with
continue.
What’s Next?
Now that you understand break and continue, we will move to another important loop control — the for-else and while-else construct in Python.
No comments:
Post a Comment