Iterate Over a Range Using While Loop

Introduction:

  • In Python, you can use a while loop to iterate over a range. This is useful when you need more control over the loop execution than a for loop provides.

How to Use While Loop with Range:

  • Initialize a counter i with the start value of the range.
  • While this counter is less than the stop value of the range, run the while loop.
  • Inside the loop, increment the counter by the step value.

Syntax:

  • To iterate over a range my_range:

    python
    i = my_range.start
    while i < my_range.stop:
        print(i)
        i += my_range.step
    

Example:

  • Iterate Over a Range Using While Loop:
    • This example shows how to iterate over a range from 4 to 8 using a while loop.
    • Python Program:

      python
      my_range = range(4, 9)
      
      i = my_range.start
      while i < my_range.stop:
          print(i)
          i += my_range.step
      
    • Output:

      4
      5
      6
      7
      8
      

Exercises:

  1. Iterate Over a Range from 1 to 5:
    • Write a program to iterate over a range from 1 to 5 using a while loop and print each number.

      python
      my_range = range(1, 6)
      i = my_range.start
      while i < my_range.stop:
          print(i)
          i += my_range.step
      
  2. Iterate Over a Range with Step 2:
    • Write a program to iterate over a range from 2 to 10 with a step of 2 using a while loop and print each number.

      python
      my_range = range(2, 11, 2)
      i = my_range.start
      while i < my_range.stop:
          print(i)
          i += my_range.step
      

Summary:

  • In this tutorial, we learned how to iterate over a range using a while loop in Python. This method provides greater control over loop execution compared to a for loop. Practice these examples to get comfortable with using while loops with ranges in your Python programs!