Python continue Statement with Examples

How to Use the continue Statement in Python

In this tutorial, you will learn what a continue statement is and how to use it in Python.

What is a continue statement in Python?

The continue statement is a control flow statement used to skip the current iteration of a loop and continue with the next iteration.

Learn more:

The continue Statement Syntax

The syntax of the continue statement is as follows:

continue

Note that continue can only occur inside a for or while loop.

Continue statement with a while loop

The while loop loops through blocks of code until the specified condition is met.

The following code shows an example of a while loop without a continue statement:

  1. count = 0
  2. while count < 10:
  3.     print (count)
  4.     count += 1

A while loop is executed, and the count variable is printed while its value is less than 10.

Output:

0
1
2
3
4
5
6
7
8
9

Now let's skip and display only when the variable count has a value of 7 or more.

This can be achieved by using a continue statement in a while loop.

  1. count = 0
  2. while count < 10:
  3.     count += 1
  4.     if count < 7:
  5.         continue
  6.     print (count)

Output:

7
8
9
10

Continue statement with a for loop statement

Like a while loop, a continue statement can be used to skip the current iteration and continue with the next iteration.

Let's look at the following example:

  1. fruits = ["Melon", "Orange", "Mango", "Melon", "Kiwi", "Orange", "Kiwi"]
  2. for fruit in fruits:
  3.     print(fruit)

The continue statement is not used. The for loop runs until all the items in the list are printed.

Output:

Melon
Orange
Mango
Melon
Kiwi
Orange
Kiwi

Now suppose we want to print only the values of the first five items. Here we use the continue statement, and the program looks like this:

  1. fruits = ["Melon", "Orange", "Mango", "Melon", "Kiwi", "Orange", "Kiwi"]
  2. count = 0
  3. length = len(fruits)
  4. for fruit in fruits:
  5.     if count <  length  and count < 5:
  6.         print(fruit)
  7.         count += 1
  8.         continue
  9.     break

The for loop is executed, and the first five items are printed. When the variable count reaches 5, the program continues and executes the next statement, but immediately terminates because of the break statement.

Output:

Melon
Orange
Mango
Melon
Kiwi

The break statement is used to exit the loop when the variable count reaches 5.

Summary

In this tutorial, you have learned what a continue statement is and how to use it in Python. A continue statement is used to skip the remaining code in the current iteration loop and continue with the next iteration.


See also:
Python return Statement with Examples
Python List Methods and Functions with Examples
Python abs() – Absolute Value in Python
Python Factorial – Find the Factorial of a Number
Python min() – Find the Smallest Value in Python

Leave a Comment