Continue Statement in Python Programming

What is the use of Continue Statement in Python?

In python, the continue keyword can alter the normal flow of a loop. Loop iterate over each element of a sequence. Continue Statement in Python: It is used to force the loop to execute. As before we have discussed the break statement, what break statement do? it terminates the loop when an element is found in a given sequence. That is the only difference between the break and continue statement in python.

The continue statement is just the opposite of a break statement. It forces the loop to execute even if the value/element is found.

Flow Diagram with a loop

continue-statement-in-python

Syntax:

#Continue statement Syntax
continue    //syntax

Let’s see one example.

Example: In this example, we will write a program to print only those numbers which are not a multiple of 5.

#continue statement example
x = [1,2,3,4,5,6,7,8,9,10]
for i in x:
    if(i%5 == 0):
        continue
    print(i)

# output
# 1
# 2
# 3
# 4
# 6
# 7
# 8
# 9

Detailed explanation of the program:

  • In the above example, we initialized a list x with some random values of integer type.
  • Next, we have used for loop to iterate over each element of list x.
  • Also, we checked for each element of x is the modulo of 5 or not.
  • If the condition is True, we are doing nothing just telling our for loop to continue iteration.
  • But when the condition is True, we are printing the result.
  • It means, except number which is the modulo of 5 is not printed. Rest all the numbers will be printed.
  • Hence, the result is obtained as output.

Python break statement vs Python continue statement

Difference between break and continue statement in python

Python break statement: The python break statement is used to break the loop during the execution of the loop when we found the required result.
Suppose, we are searching for an element with value 7 in a sequence of a list and we found that in the third iteration. But for loop continue to iterate over each element till it reaches the last element. So, in that case, we prefer to use the break statement to terminate the loop immediately.

Python continue statement: It is used to alter the normal flow of the loop. It forces the loop to continue iteration even after the result is found. It is the opposite of the break statement, i.e. break statement terminates the loop forcefully and the continue statement forces the loop to continue iteration even after getting the required result.