Continue statement in Python Examples
Demonstration of Continue statement in Python
In this example, we will use continue inside some condition within a loop.
Python3
for var in "w3wiki" : if var = = "e" : continue print (var) |
Output:
G k s f o r g k s
Explanation: Here we are skipping the print of character ‘e’ using if-condition checking and continue statement.
Printing range with Python Continue Statement
Consider the situation when you need to write a program that prints the number from 1 to 10, but not 6.
It is specified that you have to do this using a loop and only one loop is allowed to use. Here comes the usage of the continue statement. What we can do here is we can run a loop from 1 to 10 and every time we have to compare the value of the loop variable with 6. If it is equal to 6 we will use the continue statement to continue to the next iteration without printing anything, otherwise, we will print the value.
Python3
# loop from 1 to 10 for i in range ( 1 , 11 ): # If i is equals to 6, # continue to next iteration # without printing if i = = 6 : continue else : # otherwise print the value # of i print (i, end = " " ) |
Output:
1 2 3 4 5 7 8 9 10
Note: The continue statement can be used with any other loop also like the while loop, similarly as it is used with for loop above.
Continue with Nested loops
In this example, we are creating a 2d list that includes the numbers from 1 to 9 and we are traversing in the list with the help of two for loops and we are skipping the print statement when the value is 3.
Python3
# prints all the elements in the nested list # except for the ones with value 3 nested_list = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 ]] for i in nested_list: for j in i: if j = = 3 : continue print (j) |
Output
1 2 4 5 6 7 8 9
Continue with While Loop
In this example, we are using a while loop which traverses till 9 if i = 5 then skip the printing of numbers.
Python3
# prints the numbers between # 0 and 9 that are not equal to 5 i = 0 while i < 10 : if i = = 5 : i + = 1 continue print (i) i + = 1 |
Output
0 1 2 3 4 6 7 8 9
Python Continue Statement
Python Continue Statement skips the execution of the program block after the continue statement and forces the control to start the next iteration.