range(), explained simply
range(5) gives 0, 1, 2, 3, 4. But range can do much more if you give it extra numbers.
With two numbers, range(start, stop) begins at start and stops just before stop. With three, range(start, stop, step) jumps by step each time. The stop number itself is never included.
A negative step counts backwards, so range(10, 0, -2) gives 10, 8, 6, 4, 2.
Example: Hop across the stones
for stone in range(2, 11, 2):
print("Hop to stone", stone)Output
Hop to stone 2
Hop to stone 4
Hop to stone 6
Hop to stone 8
Hop to stone 10Try this
- Print the five times table using range with a step of 5.
- Count down from 10 to 1 using a negative step.
- Predict what range(3, 3) gives, then test it.
