Python continue
Summary: in this tutorial, you’ll learn about the Python continue
statement and how to use it to control the loop.
Introduction to the Python continue statement
The continue
statement is used inside a for
loop or a while
loop. The continue
statement skips the current iteration and starts the next one.
Typically, you use the continue
statement with an if
statement to skip the current iteration once a condition is True
.
The following shows how to use the continue
statement in a for
loop:
for index in range(n):
if condition:
continue
# more code here
Code language: Python (python)
And the following illustrates how to use the continue
statement in a while
loop:
while condition1:
if condition2:
continue
# more code here
Code language: Python (python)
Using Python continue in a for loop example
The following example shows how to use the for
loop to display even numbers from 0 to 9:
for index in range(10):
if index % 2:
continue print(index)
Code language: Python (python)
Output:
0
2
4
6
8
Code language: Python (python)
How it works.
- First, iterate over a range of numbers from 0 to 9 using a
for
loop with therange()
function. - Second, if the index is an odd number, skip the current iteration and start a new one. Note that the
index % 2
returns1
if theindex
is an odd number and 0 if theindex
is an even number.
Using Python continue in a while loop example
The following example shows how to use the continue
statement to display odd numbers between 0 and 9 to the screen:
# print the odd numbers
counter = 0
while counter < 10:
counter += 1 if not counter % 2:
continue
print(counter)
Code language: Python (python)
Output:
1
3
5
7
9
Code language: Python (python)
How it works.
- First, define the
counter
variable with an initial value of zero - Second, start the loop as long as the
counter
is less than 10. - Third, inside the loop, increase the
counter
by one in each iteration. If thecounter
is an even number, skip the current iteration. Otherwise, display thecounter
to the screen.
Summary
- Use the Python
continue
statement to skip the current iteration and start the next one.