Iterate Over a Range Using While Loop
Introduction:
- In Python, you can use a
whileloop to iterate over a range. This is useful when you need more control over the loop execution than aforloop provides.
How to Use While Loop with Range:
- Initialize a counter
iwith the start value of the range. - While this counter is less than the stop value of the range, run the
whileloop. - Inside the loop, increment the counter by the step value.
Syntax:
To iterate over a range
my_range:pythoni = 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
whileloop. Python Program:
pythonmy_range = range(4, 9) i = my_range.start while i < my_range.stop: print(i) i += my_range.stepOutput:
4 5 6 7 8
- This example shows how to iterate over a range from 4 to 8 using a
Exercises:
- Iterate Over a Range from 1 to 5:
Write a program to iterate over a range from 1 to 5 using a
whileloop and print each number.pythonmy_range = range(1, 6) i = my_range.start while i < my_range.stop: print(i) i += my_range.step
- 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
whileloop and print each number.pythonmy_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
whileloop in Python. This method provides greater control over loop execution compared to aforloop. Practice these examples to get comfortable with usingwhileloops with ranges in your Python programs!