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':
continue
print ('Current Letter :', letter)

Explanation

  • 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.

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 = 0
while x < 5:
x+= 1
if x == 2:
continue
print(x)

Explanation

  • Line 1: We assign the value of x to be 1.
  • Line 2: We use a 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.
  • Line 6: We print all the values of x provided the condition provided is true.

Free Resources