What is the continue statement in Python?
Overview
The continue statement in Python is used to stop an iteration that is running and continue with the next one.
How it works
The continue statement cancels every statement running in the iteration of a loop and moves the control back to the top of the loop. In simple words, it continues to the next iteration when a certain condition is reached.
We can use the continue statement in the while and for loops.
The continue statement in a for loop
In the example below, we will use the continue statement to continue to the next iteration when the letter variable is equal to o.
Code
for letter in 'Python':if letter == 'o':continueprint ('Current Letter :', letter)
Explanation
-
Line 1: We start a
forloop and give an expression that makes the variableletterrepresent all the characters of the stringPython. -
Line 2: We create a condition that if the
letteris equal to'o'in any of the iterations, the current iteration should stop, and the loop continues to the next of ('o') using thecontinuestatement in line 3. -
Line 3: We use the
continuestatement to continue to the next iteration after the'o'character in the string we created. -
Line 4: We print the statement or command to execute provided the condition provided is true.
The continue statement in a while loop
In the code below, we will use the continue statement to continue to the next iteration when x equals 2.
Code
x = 0while x < 5:x+= 1if x == 2:continueprint(x)
Explanation
- Line 1: We assign the value of
xto be1. - Line 2: We use a
whileloop for the values ofxbeing less than6starting from0(x = 0) and increasing by1in line 3. When the value ofxis equal to2using theifstatement in line 4, the iteration should continue to the next value ofxusing thecontinuestatement in line 5. - Line 6: We print all the values of
xprovided the condition provided is true.