The continue statement is used inside a loop to skip the rest of the statements in the body of loop for the current iteration and jump to the beginning of the loop for next iteration. The break and continue statements are used to alter the flow of loop, break terminates the loop when a condition is met and continue skip the current iteration.
Syntax of continue statement in Python
The syntax of continue statement in Python is similar to what we have seen in Java(except the semicolon)
continue
Flow diagram of continue
Example of continue statement
Lets say we have a list of numbers and we want to print only the odd numbers out of that list. We can do this by using continue statement.
We are skipping the print statement inside loop by using continue statement when the number is even, this way all the even numbers are skipped and the print statement executed for all the odd numbers.
# program to display only odd numbers for num in [20, 11, 9, 66, 4, 89, 44]: # Skipping the iteration when number is even if num%2 == 0: continue # This statement will be skipped for all even numbers print(num)
Output:
11 9 89
Leave a Reply