Counters and totals
The robot looks inside an empty cabinet. It has checked one more cabinet. What happened to the total number of batteries?
What happens when you use +=?
Set up a cabinet counter with count = 0. After each reading, run count += 1. With numbers, this means the same as count = count + 1. Python takes the old value, adds one and stores the result back in count. Increasing a value by one is called an increment.
Start the battery total at total = 0. Suppose stock holds the reading from the next cabinet. Then total += stock means total = total + stock. You add however many batteries you found in this cabinet to the running total.
Check each cabinet
| Cabinet | Batteries inside stock |
Cabinets checked count |
Total batteries total |
|---|---|---|---|
| Start | — | 0 | 0 |
The first cabinet holds two batteries. What will the counter and the total show?
Where do these lines go in the program?
In the starter program, for cabinet in range(3): already repeats the loop three times. For this trip, you only need to keep track of total. Keep total = 0 before the loop so the total is set to zero just once.
Inside the loop, stock = int(input()) turns the text on the cabinet display into a number. On the next line, use the same indent and add that number to the total. After the loop, at the left margin, write print(total). The log will show the total for all three cabinets.