Continue

Introduction:

  • The continue statement in Python is used to skip further instructions in the loop for the current iteration and continue with the next iteration of the loop.

Syntax:

python
continue
  • Just the continue keyword on a line by itself.

Examples:

  1. Continue Statement with While Loop:
    • This example uses a while loop to print numbers from 1 to 10. The loop skips the numbers 4 and 7.

      python
      i = 1
      while i <= 10:
          if i == 4 or i == 7:
              i += 1
              continue
          print(i)
          i += 1
      
    • Output:

      1
      2
      3
      5
      6
      8
      9
      10
      
  2. Continue Statement with For Loop and Range:
    • This example continues the execution of the for loop when the element is divisible by 3.

      python
      for x in range(1, 11):
          if x % 3 == 0:
              continue
          print(x)
      
    • Output:

      1
      2
      4
      5
      7
      8
      10
      

Exercises:

  1. Use Continue in While Loop:
    • Write a while loop to print numbers from 1 to 10. Skip the numbers 5 and 9.

      python
      i = 1
      while i <= 10:
          if i == 5 or i == 9:
              i += 1
              continue
          print(i)
          i += 1
      
  2. Use Continue in For Loop with Range:
    • Write a for loop to print numbers from 1 to 15. Skip the numbers that are multiples of 4.

      python
      for x in range(1, 16):
          if x % 4 == 0:
              continue
          print(x)
      

Summary:

  • In this tutorial, we learned how to use the continue statement to skip the execution of further statements during an iteration and continue with the next iterations or elements in the collection. Practice using the continue statement in different looping scenarios to understand its functionality and use it effectively in your Python programs!