Calculating with variables
A program that works with numbers usually reads them, stores them in variables and then calculates with the variables. This one adds up three days of running, in whole kilometers, and works out the distance per day:
monday = int(input("Monday, km: "))
tuesday = int(input("Tuesday, km: "))
wednesday = int(input("Wednesday, km: "))
total = monday + tuesday + wednesday
print(f"Distance run: {total} km")
print(f"Per day: {total / 3} km")
5
8
2Monday, km: 5
Tuesday, km: 8
Wednesday, km: 2
Distance run: 15 km
Per day: 5.0 kmAdding to a variable
Another way is to keep a running total in one variable and add each new value to it as it comes in:
total = 0
price = float(input("First item: "))
total = total + price
price = float(input("Second item: "))
total = total + price
print(f"To pay: {total}")
3.5
2.25First item: 3.5
Second item: 2.25
To pay: 5.75As before, total = total + price works out the right side first with the current values, then stores the result back in total. The total starts at 0, so the first addition has something to add to. Here one variable, price, holds each item in turn: after it's added to the total, its old value isn't needed any more.
The shorthand +=
Increasing a variable is so common that Python has a shorthand: total += price means the same as total = total + price. There are also -= and *=, and they work the same way:
balance = 100
balance += 25
balance -= 40
balance *= 2
print(balance)
170100 plus 25 is 125, minus 40 is 85, and doubled that's 170.
Keep the values you need
Reusing one variable is fine for a running total. But if the program needs every value at the end, each one needs a variable of its own:
morning = int(input("Temperature in the morning: "))
evening = int(input("Temperature in the evening: "))
print(f"From {morning} to {evening} degrees: a change of {evening - morning}")
12
19Temperature in the morning: 12
Temperature in the evening: 19
From 12 to 19 degrees: a change of 7When you do reuse a variable, keep it for values that play the same part, like the prices above. A variable value that first holds the number of guests and later the price of a ticket would work, but the reader would have to work out what it means on every line. guests and ticket_price say it at once.