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:
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.
Num = 1
Num = 2
Num = 4
Num = 5
Out of loop
Similarly, the continue statement is used in the for loop as below:
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:
- Accept the input from the user (n)
- Set the divisor (d) to 0
- Perform the following till n>1
- Check if the given number (n) is divisible by the divisor (d)
- If n%d==0
- Print d as a factor
- Set the new value of n as n/d
- Repeat from step 4
- 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.
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:
enter a number60
2
2
3
5
enter a number105
3
5
7
enter a number90
2
3
3
5