How to Skip Iteration in For Loop Python: Simple Guide
To skip an iteration in a Python
for loop, use the continue statement. When Python encounters continue, it immediately jumps to the next loop cycle, skipping the rest of the current iteration.Syntax
The continue statement is used inside a for loop to skip the current iteration and move to the next one.
Basic syntax:
for item in iterable:
if condition:
continue
# code here runs only if condition is False
Here, if condition is true, continue skips the rest of the loop body for that iteration.
python
for item in iterable: if condition: continue # code here runs only if condition is False
Example
This example prints numbers from 1 to 5 but skips printing number 3 by using continue.
python
for number in range(1, 6): if number == 3: continue print(number)
Output
1
2
4
5
Common Pitfalls
One common mistake is using continue outside a loop, which causes an error. Another is confusing continue with break. break stops the entire loop, while continue only skips the current iteration.
Wrong usage example:
if condition:
continue # Error: 'continue' not inside a loopRight usage example:
for i in range(5):
if i == 2:
continue # skips printing 2
print(i)python
for i in range(5): if i == 2: continue # skips printing 2 print(i)
Output
0
1
3
4
Quick Reference
Use continue to skip the rest of the current loop iteration and move to the next one.
Use break to exit the loop completely.
| Statement | Effect |
|---|---|
| continue | Skip current iteration, continue with next loop cycle |
| break | Exit the loop completely |
Key Takeaways
Use
continue inside a for loop to skip the current iteration.continue jumps immediately to the next loop cycle.Do not use
continue outside loops; it causes errors.break stops the whole loop, unlike continue.Place
continue after the condition that decides to skip.