This tutorial will teach you about the Python continue statement and how to use it to control the loop.
Within a for loop or a while loop, the continue statement is used. The continue statement terminates the current iteration and begins the next.
When a condition is True, you typically use the continue statement in conjunction with an if statement to skip the current iteration.
The following example demonstrates how to use the continue statement in a for loop:
for index in range(n): if condition: continue # more code here
In a while loop, the continue statement is used in the following way:
while condition1: if condition2: continue # more code here
Example of a for loop in Python with continue
The for loop is used to display even integers from 0 to 9 in the following example:
for index in range(10): if index % 2: continue print(index)
Output
0 2 4 6 8
How does it work?
Using a for loop and the range() function, iterate over a range of values from 0 to 9.
Second, start a new iteration if the index is an odd number. The index percent 2 function returns 1 if the index is odd, and 0 if the index is even.
Continue with while loop example in Python
The continue statement is used in the following example to display odd integers between 0 and 9 on the screen:
# print the odd numbers counter = 0 while counter < 10: counter += 1 if not counter % 2: continue print(counter)
Output
1 3 5 7 9
How does it work?
First, set the counter variable to zero.
Second, begin the loop while the counter is less than 10.
Third, for each iteration of the loop, increase the counter by one. Skip the current iteration if the counter is even. Otherwise, the counter should be displayed on the screen.
Leave a Reply