What is continue statement in Python?

In this article, we will discuss continue statements in Python for altering the flow of loops.

Usage of Continue Statement

Loops in Python automates and repeats the tasks in an efficient manner. But sometimes, there may arise a condition where you want to exit the loop completely, skip an iteration or ignore that condition. These can be done by loop control statements. Continue is a type of loop control statement that can alter the flow of the loop. 

Continue statement

Continue statement is a loop control statement that forces to execute the next iteration of the loop while skipping the rest of the code inside the loop for the current iteration only i.e. when the continue statement is executed in the loop, the code inside the loop following the continue statement will be skipped for the current iteration and the next iteration of the loop will begin.

In Python, the continue statement is a control flow statement that is used inside loops, such as for or while loops, to skip the current iteration of the loop and move on to the next iteration. When a continue statement is encountered, the program skips all the remaining statements in the current iteration and jumps to the next iteration of the loop.

The continue statement is particularly useful when you want to skip certain iterations of a loop based on certain conditions. For example, consider the following for loop that prints all even numbers between 1 and 10:

 

for i in range(1, 11):
    if i % 2 != 0:
        continue
    print(i)

In this code, the if statement checks if the current value of i is odd or even. If i is odd, the continue statement is executed, which skips the remaining statements in the current iteration and jumps to the next iteration of the loop. If i is even, the program continues to execute the remaining statements in the loop, which prints the value of i.

The output of this code would be: 

 

2
4
6
8
10

Note that the value 1 is skipped because it is odd and the continue statement is executed, which skips the print statement for 1 and moves to the next iteration of the loop.

Submit Your Programming Assignment Details