Continue statement in Python
In this lesson, you will learn about the continue statement in Python, its syntax and how to use it in for loop and while loop.
Loop Control Statement in Python
When you have to override a loop or you need to exit the loop or omit an iteration based on an external condition, you use loop control statements. Loop control statements exit the loop when a certain external condition is met and execute the immediate next line of code after the loop. Loop control statements change execution from its normal sequence.
Python supports the following loop control statements:
- break
- continue
Continue Statement in Python
The continue statement in python returns the control to the beginning of the loop. It excludes the remaining statements in the loop and begins from the first. By using this, we can omit a value while traversing the sequence. This loop is applicable for both for loop and while loop in python.
Syntax:
continue
Now let’s see the use of continue statement in a program in python loops
Sample program using continue statement in while loop.
Input
[gamipress_button type=”submit” label=”Run Code Snippet” onclick=”window.open(‘https://coderseditor.com/?id=1307′,’_blank’)”]
i = 57 while i < 72: i += 2 if i == 65: continue print(i)
Output:
59 61 63 67 69 71 73
In the result, you can see that the loop prints the values from 59-73 with the addition of two in each value. We have confined the loop to skip the value 65 by using the continue statement. When the loop reaches the value of 65, the continue statement gets executed and then the iteration begins from the beginning of the loop skipping the 65.
Sample program using the continue statement in for loop
Input:
[gamipress_button type=”submit” label=”Run Code Snippet” onclick=”window.open(‘https://coderseditor.com/?id=1308′,’_blank’)”]
for x in range(57, 75): if x == 65: continue else: print(x)
Output:
57 58 59 60 61 62 63 64 66 67 68 69 70 71 72 73 74