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 hereCode language: Python (python)
And the following illustrates how to use the continue statement in a while loop:
while condition1: if condition2: continue # more code hereCode 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 8Code language: Python (python)
How it works.
- First, iterate over a range of numbers from 0 to 9 using a
forloop with therange()function. - Second, if the index is an odd number, skip the current iteration and start a new one. Note that the
index % 2returns1if theindexis an odd number and 0 if theindexis 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 9Code language: Python (python)
How it works.
- First, define the
countervariable with an initial value of zero - Second, start the loop as long as the
counteris less than 10. - Third, inside the loop, increase the
counterby one in each iteration. If thecounteris an even number, skip the current iteration. Otherwise, display thecounterto the screen.
Leave a Reply