Python Continue Statement with Examples


How to Use the Python Continue Statement

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

What is a Continue Statement in Python?

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

The syntax of the continue statement is as follows:

continue

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

Continue with a While Loop

As you may know, a while loop iterates over a block of code until a certain condition is met. The following is an example illustrates a while loop without a continue statement:

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

0
1
2
3
4
5
6
7
8
9

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

Now, let's say we want to skip and print the value of the count variable only if it is greater than or equal to 7. This can be done using the continue statement inside the while loop as illustrated in the following example:

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

7
8
9
10

Continue with a For Loop

Like the while loop, the for loop can be skipped the current iteration and continue with the next iteration using the continue statement.

The following example illustrates the for loop without the continue statement:

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

Melon
Orange
Mango
Melon
Kiwi
Orange
Kiwi

As you can see, the for loop runs until it prints all items in the list.

Now let's say we want to print the values of the first 5 items only. This can be done using the continue statement as follows:

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

print("The of value of count is", count)

In this program, the for loop runs and prints the items in the list as long as count is less than len and 5. And when count is 5, the loop continues to execute the next statement inside the loop. But the loop exits immediately when count is 5.

Melon
Orange
Mango
Melon
Kiwi
The of value of count is 5

Note that the break statement is used to exit the loop in the above example. Please take a look at the following link if you want learn more about the break statement:

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

Leave a Reply

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