The continue
statement in Python is used to stop an iteration that is running and continue with the next one.
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.
continue
statement in a for
loopIn the example below, we will use the continue
statement to continue to the next iteration when the letter
variable is equal to o
.
for letter in 'Python':if letter == 'o':continueprint ('Current Letter :', letter)
Line 1: We start a for
loop and give an expression that makes the variable letter
represent all the characters of the string Python
.
Line 2: We create a condition that if the letter
is equal to 'o'
in any of the iterations, the current iteration should stop, and the loop continues to the next of ('o'
) using the continue
statement in line 3.
Line 3: We use the continue
statement 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.
continue
statement in a while
loopIn the code below, we will use the continue
statement to continue to the next iteration when x
equals 2
.
x = 0while x < 5:x+= 1if x == 2:continueprint(x)
x
to be 1
.while
loop for the values of x
being less than 6
starting from 0
(x = 0
) and increasing by 1
in line 3. When the value of x
is equal to 2
using the if
statement in line 4, the iteration should continue to the next value of x
using the continue
statement in line 5.x
provided the condition provided is true.