The range() Function
range() produces a sequence of numbers to loop over — handy when you want to
repeat something a set number of times, or step through a run of values.
range(stop)
Counts from 0 up to but not including stop:
for i in range(5):
print(i)
This prints 0, 1, 2, 3 and 4, each on its own line: five iterations in total. The stop value 5 is not included.
range(start, stop)
Counts from start up to but not including stop:
for face in range(2, 7):
print(face)
range(2, 7) gives 2, 3, 4, 5, 6. The stop value 7 is never reached — a
neat way to step through the faces of a die that aren't 1.
The stop value is left out
This trips up nearly everyone at first: the number you pass as stop is
not included. To include a number, aim one past it. list() shows the
whole sequence at once:
print(list(range(1, 10)))
print(list(range(1, 11)))
The first one stops at 9. To get all the way to 10, the stop value has to
be 11.
Optional: choosing a step
A third argument specifies how much the value changes each time:
for number in range(2, 9, 2):
print(number)
This prints 2, 4, 6 and 8, on separate lines. The stop value is still excluded.
A negative step counts down:
for number in range(3, 0, -1):
print(number)
This prints 3, 2 and 1. You do not need the step argument for Repeated Greetings or Times Table.
For positions in a non-empty string of length n, the last index is n - 1. A negative step must move towards a smaller, excluded stop. With range(2, -1, -1), the values are 2, 1 and 0; -1 itself is not visited. If the starting value already equals the stop, the range is empty.
Counting while you loop
range() pairs naturally with a running count — see
the accumulator pattern.
See also: For loops, The accumulator pattern.
Your turn
Add a loop that uses range() to print the numbers 1 to 5 — remember,
the stop value is left out.
# add a two-line loop using range()
Expected output
1
2
3
4
5
Practise this in the free Python course, where every exercise checks your code instantly.