When learning Python, one of the first concepts you'll encounter is the range() function. It is commonly used with loops to repeat tasks a specific number of times.
Instead of using random numbers, let's understand range() through simple real-life examples.
What is range()?
The range() function generates a sequence of numbers.
Syntax
range(start, stop, step)
- start → The number where the sequence begins.
- stop → The sequence ends before this number.
- step → The amount by which the numbers increase or decrease.
Example 1: Assigning Roll Numbers
Imagine five students enter a classroom one after another.
- First student → Roll Number 1
- Second student → Roll Number 2
- Third student → Roll Number 3
- Fourth student → Roll Number 4
- Fifth student → Roll Number 5
Code
for i in range(1, 6):
print(i)
Output
1
2
3
4
5
Explanation
range(1, 6)
starts from 1 and stops before 6, so Python prints:
1 → 2 → 3 → 4 → 5
Example 2: Even Queue Positions
A coach asks students to stand only in even-numbered positions.
The first five even positions are:
2, 4, 6, 8, 10
Code
for a in range(2, 12, 2):
print(a)
Output
2
4
6
8
10
Explanation
range(2, 12, 2)
- Starts at 2
- Stops before 12
- Increases by 2 every time
Sequence:
2 → 4 → 6 → 8 → 10
Example 3: Lift Stops Every Third Floor
A newly constructed building has a lift that stops only at every third floor for safety reasons.
Starting from the ground floor, display the first five stops.
Code
for b in range(0, 15, 3):
print(b)
Output
0
3
6
9
12
Explanation
range(0, 15, 3)
- Starts from floor 0
- Stops before 15
- Moves 3 floors each time
Sequence:
0 → 3 → 6 → 9 → 12
Example 4: Rocket Countdown
A rocket launches with a countdown using only even numbers.
Code
for c in range(10, -1, -2):
print(c)
Output
10
8
6
4
2
0
Explanation
range(10, -1, -2)
- Starts at 10
- Counts backward
- Decreases by 2
- Stops after printing 0
Sequence:
10 → 8 → 6 → 4 → 2 → 0
Understanding the Three Parameters
| Parameter | Meaning | Example |
|---|---|---|
| Start | Where counting begins | 1 |
| Stop | Stops before this value | 6 |
| Step | Increment or decrement |
2 or -2
|
Example:
range(1, 6)
Produces:
1 2 3 4 5
Example:
range(10, -1, -2)
Produces:
10 8 6 4 2 0
Why Use range()?
The range() function makes loops simple and efficient.
It helps when you need to:
- Assign serial numbers
- Print even or odd numbers
- Generate countdowns
- Skip numbers with custom intervals
- Repeat tasks multiple times
Final Thoughts
The range() function is one of the most useful tools in Python programming. Once you understand its three parameters—start, stop, and step—you can solve many looping problems with ease.
Using real-life examples like roll numbers, queue positions, lift stops, and rocket countdowns makes learning range() much more intuitive.
Top comments (0)