range()
range() produces a sequence of integers, from a start up to an end that is not included.
Used in 34 lessons of the course, from 00.03.
range() gives you whole numbers in order, without you typing each one.
It has three forms:
range(stop)counts from 0 up tostop - 1.range(start, stop)begins atstart.range(start, stop, step)jumps bystep.
The stop value is never included. So range(1, 4) gives 1, 2, 3. This is a Python convention that makes range(n) have exactly n items.
range does not build a full list in memory. It computes each number when asked, so it is cheap even for millions of values. If you need to see them together, use list(range(...)).
The course writes for step in range(1, STEPS + 1):. It adds 1 to the end so the last step, STEPS, is included, and starts at 1 so steps are counted the way a person would count.
Reach for it when: you need to repeat something a set number of times, or walk through numbers with a `for` loop.
Examples
Common mistake
for n in range(1, 3):
print(n)Why: You may expect 1, 2 and 3, but the end is never included, so 3 is not printed.
How to write it: Add 1 to the end: range(1, 4).
Common mistake
for i in range(5, 1):
print(i)
print("done")Why: With a positive step, if the start is already past the end, the range is empty and the loop never runs.
How to write it: Use a negative step: range(5, 1, -1).
