Python Continue Statement with Examples


How to Use the continue Statement in Python

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

What is a continue statement in Python?

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

The continue Statement Syntax

The syntax of the continue statement is as follows:

continue

Note that continue may only occur nested in a for or while loop.

The continue Statement with the while Loop

The while loop loops through a block of code until it meets a specified condition. 

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

count = 0
while count < 10:
    print (count)
    count += 1

Here, in this example, the while loop runs and prints the value of the count variable as long as it is less than 10.

Output:

0
1
2
3
4
5
6
7
8
9

Now, let's say you want to skip and print the value of the count variable only if it is greater than or equal to 7. 

You can achieve this using the continue statement inside the while loop.

Here is an example:

count = 0
while count < 10:
    count += 1
    if count < 7:
        continue
    print (count)

Output:

7
8
9
10

The continue Statement with the for Loop

Like the while loop, you can skip the current iteration and continue with the next iteration using the continue statement.

Let's take a look at the following example:

fruits = ["Melon""Orange""Mango""Melon""Kiwi""Orange""Kiwi"]
for fruit in fruits:
    print(fruit)

Here, without using the continue statement, the for loop runs until it prints all items of the list.

Output:

Melon
Orange
Mango
Melon
Kiwi
Orange
Kiwi

Now let's say you want to print the values of the first five items only. Here, we use the continue statement, and the program will like this:

fruits = ["Melon""Orange""Mango""Melon""Kiwi""Orange""Kiwi"]
count = 0
length = len(fruits)
for fruit in fruits:
    if count <  length  and count < 5:
        print(fruit)
        count += 1
        continue
    break

In the above example, the for loop runs and prints the first five items. When the variable count reaches 5, the program continues to execute the next statement but exits immediately because of the break statement. 

Output:

Melon
Orange
Mango
Melon
Kiwi

Note that the break statement used to exit the loop as soon as the variable count reaches 5 in the above example.

In this tutorial, you've learned what a continue statement is and how to use it. In Python, a continue statement used to skip the rest of the code in a loop for the current iteration and continue with the next iteration.

Leave a Reply

Your email address will not be published. Required fields are marked *