Line At A Time
Lesson 19: Adding It Up
Adding It Up Total up all the numbers in a list.
1prices = [2, 4, 6]
2total = 0
3for price in prices:
4 total = total + price
5print(total)
Terminal
$ python3 main.py
12
Every line, explained
prices = [2, 4, 6]
A list stores several values in one variable. The values go between square brackets, separated by commas. Lists are one of Python's favourite tools, and unlike some languages, you can print one directly and see its contents. This one holds numbers; a list can hold any kind of value.
total = 0
This creates a variable: a named box that stores a value. In Python you just write name = value: the = stores the value on the right into the name on the left. No special type word, no semicolon; Python keeps it simple. total starts at 0 and will collect the running sum.
for price in prices:
for ... in ... visits each item in the list, one trip around the loop per item. Each time, the loop variable holds the current item. Like if, the line ends with a colon and the loop's body is indented.
total = total + price
Each trip around the loop adds the current price onto total: 0+2=2, 2+4=6, 6+6=12. (Python also has a shortcut for this: total += price.)
print(total)
print(...) shows whatever is inside its round brackets in the terminal, then moves to a new line. It is written all in lowercase, and it needs both brackets. Look closely: this line is NOT indented, so it is outside the loop and runs just once, at the end. Indentation decides what is inside the loop!