In this tutorial you’ll learn about continue statement in Python which is used inside a for loop or while loop to go back to the beginning of the loop. When continue statement is encountered in a loop control transfers to the beginning of the loop, any subsequent statements with in the loop are not executed for that iteration.
Common use of continue statement is to use it along with if condition in the loop. When the condition is true the continue statement is executed resulting in next iteration of the loop.
continue statement Python examples
1- Using continue statement with for loop in Python. In the example a for loop in range 1..10 is executed and it prints only odd numbers.
for i in range(1, 10): # Completely divisble by 2 means even number # in that case continue with next iteration if i%2 == 0: continue print(i) print('after loop')
Output
1 3 5 7 9 after loop
2- Using continue statement in Python with while loop. In the example while loop is iterated to print numbers 1..10 except numbers 5 and 6. In that case you can have an if condition to continue to next iteration when i is greater than 4 and less than 7.
i = 0 while i < 10: i += 1 if i > 4 and i < 7: continue print(i)
Output
1 2 3 4 7 8 9 10
3- Here is another example of using continue statement with infinite while loop. In the example there is an infinite while loop that is used to prompt user for an input. Condition here is that entered number should be greater than 10, if entered number is not greater than 10 then continue the loop else break out of the loop.
while True: num = int(input("Enter a number greater than 10: ")) # condition to continue loop if num < 10: print("Please enter a number greater than 10...") continue else: break print("Entered number is", num)
Output
Enter a number greater than 10: 5 Please enter a number greater than 10... Enter a number greater than 10: 16 Entered number is 16
That's all for this topic Python continue Statement With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Python Tutorial Page
Related Topics
You may also like-
No comments:
Post a Comment