Python continue Statement
continue is the keyword in Python used to skip the current loop iteration and move to the next one.
The difference between break in Vue 2,continue It does not terminate the whole loop; it only skips the remaining code in the current iteration.
Word meaning: continue means "continue": skip the current iteration and move to the next.
Basic syntax and parameters
continue It is a standalone statement and requires no arguments.
Syntax format
for item in iterable:
if skip condition:
continue
# Process code
Use Cases
- Skip specific elements: skip processing when a condition is met.
- Filter data: exclude data that does not meet the condition.
- Simplify logic: move "do not process" conditions earlier to reduce nesting.
Example
Example 1: skipping even numbers
Example
Print the odd numbers from 1 to 10
for
i
in
range
(
1
,
11
)
:
if
i %
2
==
0
:
continue
Skip even numbers
(
i
,
end
=
" "
)
(
)
Output: 1 3 5 7 9
Expected output:
1 3 5 7 9
Code analysis:
- When i is even, continue is executed, skipping the following print.
- When i is odd, print is executed normally.
Example 2: filtering list elements
Example
Filter out empty values and None
data
=
[
"apple"
,
None
,
""
,
"banana"
,
" "
,
"cherry"
]
Method 1: using continue
result
=
[
]
for
item
in
data:
if
not
item:
An empty string or None is False
continue
result.
append
(
item
)
(
result
)
Output: ['apple', 'banana', ' ', 'cherry']
Method 2: only process valid entries
(
"Valid data:"
)
for
item
in
data:
if
item:
Non-empty and not None
(
f
"- {item}"
)
Expected output:
['apple', 'banana', ' ', 'cherry']
Valid data:
- apple
- banana
-
- cherry
continue can be used to filter data and exclude unwanted elements.
Example 3: using continue in a while loop
Example
Simulate skipping specific numbers
n
=
0
while
n
<
10
:
n +
=
1
if
n
==
5
or
n
==
7
:
continue
Skip 5 and 7
(
n
,
end
=
" "
)
(
)
Output: 1 2 3 4 6 8 9 10
Expected output:
1 2 3 4 6 8 9 10
continue works the same way in a while loop.
Example 4: simplifying code logic
Example
Use continue to simplify logic
numbers
=
[
1
,
2
,
3
,
4
,
5
,
6
,
7
]
Without continue (deeper nesting)
(
"Positive numbers (method 1):"
)
for
n
in
numbers:
if
n
0
:
(
n
)
(
"\nPositive numbers (method 2) - using continue):"
)
for
n
in
numbers:
if
n
<=
0
:
continue
(
n
)
(
"\nNegative numbers:"
)
for
n
in
numbers:
if
n
=
0
:
continue
(
n
)
Expected output:
Using continue makes code flatter and reduces nesting.
Example 5: continue in nested loops
Example
continue only affects the current loop
for
i
in
range
(
1
,
4
)
:
for
j
in
range
(
1
,
4
)
:
if
j
==
2
:
continue
Skip the current iteration of the inner loop
(
f
"({i},{j})"
,
end
=
" "
)
(
)
Expected output:
(1,1) (1,3)
(2,1) (2,3)
(3,1) (3,3)
continue only skips the current iteration of the innermost loop containing it.
Python3 loop statements