CodeBlanks Logo Icon CodeBlanks

range

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 4

range(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 ... 1

A 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

main.py
# Loop with range

Sample solution

main.py
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

Question
for i in ____(5):
    print(i)
Answer
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

All lessons in Beginner