Sub topic 3
Counting with range(): start, stop, step
This chapter assumes you can write and run a Python 3 script. It also assumes you know variables, indentation, print(), and how a basic for loop walks over a list.
Why range() exists
A for loop needs something to iterate over. When you want to repeat an action a set number of times, or walk through numbers, range() supplies the integers.
The three forms
range() accepts one, two, or three integer arguments.
print(list(range(5))) # [0, 1, 2, 3, 4]
print(list(range(2, 8))) # [2, 3, 4, 5, 6, 7]
print(list(range(0, 10, 3))) # [0, 3, 6, 9]The forms work like this:
range(stop)starts at 0 and counts up to, but not including,stop.range(start, stop)starts atstartand stops beforestop.range(start, stop, step)addsstepeach time instead of 1.
The stop value is always excluded. This is the source of most off-by-one errors.
Using range in a loop
for i in range(1, 4):
print("Pass", i)This prints Pass 1, Pass 2, and Pass 3. To repeat something five times, write for _ in range(5):. The name _ tells readers you do not use the counter.
Choosing bounds
Two rules help you avoid off-by-one mistakes:
len(range(start, stop))equalsstop - startwhen the step is 1. Sorange(3, 8)gives 5 values.- To include an end value in an upward count, pass
end + 1.
# Numbers 1 through 10, inclusive
for n in range(1, 11):
print(n, end=" ")
print()Rules for the arguments
- All arguments must be integers.
range(2.5)andrange(0, 1, 0.1)raiseTypeError. - The step cannot be 0.
range(0, 5, 0)raisesValueError. - If
startis already at or paststop(for a positive step), the range is empty and the loop body never runs.
print(list(range(5, 2))) # []For fractional steps, compute the value from an integer counter instead:
for i in range(5):
print(i * 0.1)A worked example
This program sums the multiples of 3 below 20:
total = 0
for n in range(0, 20, 3):
total += n
print(total) # 0 + 3 + 6 + 9 + 12 + 15 + 18 = 63The loop visits 0, 3, 6, 9, 12, 15, and 18. The next value, 21, is not below 20, so the loop ends.
Common errors
| Mistake | Result | Fix |
|---|---|---|
| `range(1, 10)` expecting 10 | Stops at 9 | Use `range(1, 11)` |
| `range(0.5, 3)` | `TypeError` | Use integers |
| `range(0, 5, 0)` | `ValueError` | Use a nonzero step |
| `range(5, 0)` expecting a countdown | Empty range | Add a negative step (next chapter) |
Exercise
What values does list(range(4, 20, 5)) produce, and why is 19 not included?
Show answer
It produces [4, 9, 14, 19]? No. Start at 4, add 5 each time: 4, 9, 14, 19. Since 19 is less than 20, it is included, so the result is [4, 9, 14, 19]. The stop value 20 is the only excluded boundary, and the sequence stops because the next value, 24, is not below 20.
Exercise
Write a loop with range() that prints every even number from 2 to 10 inclusive.
Show answer
for n in range(2, 11, 2): print(n). The stop is 11 so that 10 is included, and the step of 2 skips the odd numbers.