For i in range()

Introduction:

  • In Python, you can use the range() function with a for loop to iterate over a sequence of numbers. This is a fundamental concept for looping and iteration in Python.

Syntax:

  • Here are some common ways to use range() with for loops:

    python
    for i in range(x):
        # statements(s)
    
    for i in range(x, y):
        # statements(s)
    
    for i in range(x, y, step):
        # statements(s)
    
    for i in range(start, stop, step):
        # statements(s)
    

Examples:

  1. for i in range(x):
    • This loop iterates from 0 to x-1.
    • Python Program:

      python
      for i in range(5):
          print(i)
      
    • Output:

      0
      1
      2
      3
      4
      
  2. for i in range(x, y):
    • This loop iterates from x to y-1.
    • Python Program:

      python
      for i in range(5, 10):
          print(i)
      
    • Output:

      5
      6
      7
      8
      9
      
  3. for i in range(x, y, step):
    • This loop iterates from x to y-1 in steps of step.
    • Python Program:

      python
      for i in range(5, 15, 3):
          print(i)
      
    • Output:

      5
      8
      11
      14
      
  4. for i in range(start, stop, step):
    • This loop iterates from start to stop in steps of step.
    • Python Program:

      python
      for i in range(15, 5, -3):
          print(i)
      
    • Output:

       
      15
      12
      9
      6
      

Exercises:

  1. Print Even Numbers:
    • Write a program to print even numbers from 0 to 10 using range().

      python
      for i in range(0, 11, 2):
          print(i)
      
  2. Print Numbers in Reverse:
    • Write a program to print numbers from 10 to 1 using range().

      python
      for i in range(10, 0, -1):
          print(i)
      
  3. Print Multiples of 3:
    • Write a program to print multiples of 3 from 3 to 30 using range().

      python
      for i in range(3, 31, 3):
          print(i)
      

Summary:

  • In this tutorial, we learned how to use the for loop with range() in Python. This is a basic and essential concept for looping and iteration in Python. Practice these examples to get comfortable with for loops and range() in your Python programs!