PYTHON - continue Statement
Python - Continue Statement
Python continue Statement
Pythoncontinue statementis used to skip the execution of the program block and returns the control to the beginning of the currentloopto start the next iteration. When encountered, the loop starts next iteration without executing the remaining statements in the current iteration.
Thecontinue statementis just the opposite to that ofbreak. It skips the remaining statements in the current loop and starts the next iteration.
Syntax of continue Statement
looping statement:
condition check:
continueFlow Diagram of continue Statement
The flow diagram of the continue statement looks like this −
Python continue Statement with for Loop
InPython, the continue statement is allowed to be used with afor loop. Inside the for loop, you should include anif statementto check for a specific condition. If the condition becomes TRUE, the continue statement will skip the current iteration and proceed with the next iteration of the loop.
Example
Let’s see an example to understand how thecontinue statementworks in for loop.
for letter in 'Python':
if letter == 'h':
continue
print ('Current Letter :', letter)
print ("Good bye!")When the above code is executed, it produces the followingoutput−
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Good bye!Python continue Statement with while Loop
Pythoncontinue statementis used with ‘for’ loops as well as ‘while’ loops to skip the execution of the current iteration and transfer the program’s control to the next iteration.
Example: Checking Prime Factors
Following code uses continue to find the prime factors of a given number. To find prime factors, we need to successively divide the given number starting with 2, increment the divisor and continue the same process till the input reduces to 1.
num = 60
print ("Prime factors for: ", num)
d=2
while num > 1:
if num%d==0:
print (d)
num=num/d
continue
d=d+1On executing, this code will produce the followingoutput−
Prime factors for: 60
2
2
3
5Assign different value (say 75) to num in the above program and test the result for its prime factors.
Prime factors for: 75
3
5
5