The Python continue Statement is a loop control keyword used inside for and while loops to skip the rest of the current iteration and jump directly to the next cycle of the loop. When continue is encountered, Python immediately transfers control back to the beginning of the loop, ignoring any statements that follow within that iteration.
The common use case for continue statement is to pair it with if condition with in the loop to selectively skip certain iterations. 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 with while loop in Python. 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