Quantcast
Channel: Tech Tutorials
Viewing all articles
Browse latest Browse all 938

Python continue Statement With Examples

$
0
0

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

  1. Python break Statement With Examples
  2. pass Statement in Python
  3. Encapsulation in Python
  4. Constructor in Python - __init__() function
  5. Namespace And Variable Scope in Python

You may also like -

  1. What Are JVM, JRE And JDK in Java
  2. Equality And Relational Operators in Java
  3. Lambda Expressions in Java 8
  4. Reflection in Java
  5. How to Find First Non-Repeated Character in a Given String - Java Program
  6. What is Hadoop Distributed File System (HDFS)
  7. Circular Dependency in Spring Framework
  8. Sending Email Using Spring Framework Example

Viewing all articles
Browse latest Browse all 938

Trending Articles