Ranges, steps, and totals

Lesson 29 of 54 · Python Foundations

A three-argument range is range(start, stop, step). The step determines the spacing between supplied values. Positive steps move upward; negative steps move downward. The stop remains excluded, and a zero step raises ValueError.

for number in range(2, 9, 2):
    print(number)
print("down")
for number in range(12, 3, -3):
    print(number)
2
4
6
8
down
12
9
6

The downward sequence starts at 12 and subtracts 3 each time; 3 is excluded. range(12, 3) is empty because its default step is positive and cannot move toward a smaller stop. To include 3, use a stop smaller than 3, such as range(12, 2, -3).

Keep a running total

An accumulator is a variable that holds a result across iterations. Start it outside the loop, add each contribution inside, then use the final value after the loop.

total = 0
for minutes in range(1, 6, 2):
    total += minutes
    print(minutes, total)
print("Total:", total)
1 1
3 4
5 9
Total: 9

The selected values are 1, 3, and 5. The running total changes from 0 to 1, 4, and 9. Initializing total inside the loop would reset it on every pass. If the range is empty, the body never runs and the initial total remains zero.

Chapter index