How to Use Continue in Python: Simple Guide with Examples
In Python, the
continue statement is used inside loops to skip the current iteration and move to the next one immediately. It helps you avoid executing the remaining code in the loop body for specific conditions.Syntax
The continue statement is used inside for or while loops. When Python encounters continue, it skips the rest of the code inside the loop for the current iteration and jumps to the next iteration.
- continue: The keyword that tells Python to skip to the next loop cycle.
python
for item in iterable: if condition: continue # code here runs only if condition is False
Example
This example shows how continue skips printing even numbers in a loop from 1 to 5.
python
for number in range(1, 6): if number % 2 == 0: continue print(number)
Output
1
3
5
Common Pitfalls
One common mistake is using continue outside loops, which causes an error. Another is forgetting that continue only skips the current iteration, not the whole loop.
Also, overusing continue can make code harder to read if not used carefully.
python
i = 0 # Wrong: continue outside loop causes error # continue # Uncommenting this line will raise SyntaxError for i in range(3): if i == 1: continue # Skips printing 1 print(i)
Output
0
2
Quick Reference
Use continue to skip the rest of the loop body for the current iteration and proceed to the next iteration immediately.
- Works only inside loops (
for,while). - Helps avoid nested
ifstatements by skipping unwanted cases early. - Does not exit the loop, only skips current iteration.
Key Takeaways
Use
continue inside loops to skip the current iteration and move to the next one.continue helps control loop flow by avoiding execution of code below it for specific conditions.Never use
continue outside loops; it will cause a syntax error.Overusing
continue can reduce code readability, so use it wisely.continue does not stop the loop; it only skips to the next iteration.