Online Tutorials & Training Materials | STechies.com
Register Login

Use of Continue Statement in Python with Example

|| 0

Use of Continue Statement in Python with Example
Stechies

In python continue statement terminates all the remaining iteration and move the control back to the beginning of the loop for next iteration.

The continue statement can be used in both while and for loops. Here in this article we have explained continue statement examples with for and while loop.

Python Continue Statement

Python Continue Statement with for loop

Example with for loop:

# Python program to explain continue statement with for loop
string1 = "Stechies"

# Continue with for loop
for value in string1:

  # Check if string value is equal to letter 'e'
  if value == 'e':

    # If Letter is equal to 'e' next statement will skip
    continue

    # Skip statement after continue
    print('This is continue block: ',value)

  # Print the next iteration 
  print("Value: ",value)
 
# Outside the for loop 
print("Outside for Loop")

Output:

Value:  S
Value:  t
Value:  c
Value:  h
Value:  i
Value:  s
Outside for Loop

Python Continue Statement with While loop

Example with While loop:

#Python program to explain continue statement with while loop

i = 0

# Continue with while loop
while (i <= 10):
  i = i + 1

  # Check if value of i variable is equal to 5
  if i == 5:
   
    # If value is equal to 5 next statement will skip
    continue

    # Skip statement after continue
    print("This is continue block:", i)

  # Print the next iteration 
  print("Value of i:", i)

# Outside the for loop
print("Outside While Loop")

Output:

Value of i: 1
Value of i: 2
Value of i: 3
Value of i: 4
Value of i: 6
Value of i: 7
Value of i: 8
Value of i: 9
Value of i: 10
Value of i: 11
Outside While Loop