Python - continue Keyword

The effect of a continue statement is somewhat opposite to the break keyword. Instead of abandoning the pending iterations in the loop, the continue statement skips the remaining statements in the current loop and starts the next iteration.

Usage of continue in Python is shown below:

Example: continue
num=0
while num<5:
    num=num+1        
    if num==3:
        continue
    print ("Num =  {} ".format(num))
print ("Out of loop")

When num is 3, the print statement in the loop will be skipped. For other values of num, the print statement will be executed before the end of the loop message.

Output
Num = 1
Num = 2
Num = 4
Num = 5
Out of loop

Similarly, the continue statement is used in the for loop as below:

Example: continue in for loop
for num in range(1,6):        
    if num==3:
        continue
    print ("Num =  {} ".format(num))
print ("Out of loop")

The following program uses this behaviour of the continue keyword effectively. The objective of the program is to compute the prime factors of any number. The process of finding the prime factors is as follows:

  1. Accept the input from the user (n)
  2. Set the divisor (d) to 0
  3. Perform the following till n>1
  4. Check if the given number (n) is divisible by the divisor (d)
  5. If n%d==0
    • Print d as a factor
    • Set the new value of n as n/d
    • Repeat from step 4
  6. else
    • Increment d by 1
    • Repeat from step 3

This is how it is done manually. Let us say we have to factorize 60. Hence 60=2X2X3X5

The following code performs this process programmatically.

Example:
num=int(input("enter a number"))
d=2
while num>1:
    if num%d==0:
        print (d)
        num=num/d
        continue
    d=d+1

Here, continue causes the division of the input number by the same value of the divisor repetitively. The next value of the divisor is taken only after the division is not possible.

Few sample executions of the above code are shown here:

Output
enter a number60
2
2
3
5
enter a number105
3
5
7
enter a number90
2
3
3
5