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:
count = 0 while count < 10: print (count) 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.
count = 0 while count < 10: count += 1 if count < 7: continue 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:
fruits = ["Melon", "Orange", "Mango", "Melon", "Kiwi", "Orange", "Kiwi"] for fruit in fruits: 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:
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
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.