range
- Python course
- Beginner
- Lesson 43/116
- 4 min
Learn number sequences with range().
The range function
range generates a number range. range(5) generates 0 through 4:
for i in range(5):
print(i) # 0 1 2 3 4range(2, 6) gives 2 through 5. range(0, 10, 2) gives 0 to 9 in steps of 2 (0, 2, 4, 6, 8). range is not a list but a range object; to convert use list(range(5)).
The range step parameter
range can take three parameters: range(start, stop, step):
for i in range(0, 10, 2):
print(i) # 0 2 4 6 8
for i in range(10, 0, -1):
print(i) # 10 9 8 ... 1A negative step counts backwards. This is handy for countdowns and skipping loops.
Practice Print with range
Write for i in range(3): print(i).
Starter code
# Loop with rangeSample solution
for i in range(3):
print(i)Expected output
0 1 2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What numbers does range(3) produce?
- 1, 2, 3
- 0, 1, 2 Correct answer
- 0, 1, 2, 3
- 3
Explanation: range(3) produces 0, 1, 2.
2 Complete range
for i in ____(5):
print(i)
for i in range(5):
print(i)
Explanation: Number ranges use range.
3 Match the range forms
| Term | Meaning |
|---|---|
range(5) |
0-4 |
range(2, 6) |
2-5 |
range(0, 10, 2) |
0,2,4,6,8 |
range(10, 0, -1) |
10 down to 1 |