| LM | FOR Loop in range() |
What are For-Loops?
For-loops are a core structure in Python that repeat a block of code multiple times. They are ideal when the number of repetitions is known in advance. In Python, the most common way to repeat something a fixed number of times is by using the range() function.
▶ Basic Example
for i in range(5):
print(i)
Output:
0
1
2
3
4
You can use range(start, stop) to repeat something from a starting number up to, but not including, a stopping number:
for i in range(7, 11):
print(i)
Output:
7
8
9
10
range(7, 11)includes 7 but excludes 11.
The variable i is updated automatically in each step. You should not change it inside the loop body.
Stepping Through the Range
You can also define a step size with range(start, stop, step).
Example 1: Every second number
for i in range(0, 10, 2):
print(i)
Output:
0
2
4
6
8
Example 2: Check for even numbers
for i in range(6):
if i % 2 == 0:
print(i, "is even")
This loop checks each number from 0 through 5 and prints the even numbers.
Counting Down
If you want to count backwards, use a negative step:
for i in range(5, 0, -1):
print(i)
Output:
5
4
3
2
1
Make sure that the
startis greater than thestopwhen using a negative step.
Summary
range(n)loops from 0 to n-1.range(start, stop)loops fromstarttostop - 1.range(start, stop, step)controls how much the number increases (or decreases).- You can loop forwards or backwards using
range().
These loops are very useful when you want to do something a specific number of times or when working with positions like indexes in a list.