Menu

Arithmetic Operations

Arithmetic in Python programs

Arithmetic operators are most useful inside a short program that solves a real problem: values come in, a formula is applied, and the answer is stored in a variable or displayed.

width = int(input('Poster width in cm: '))
height = int(input('Poster height in cm: '))
print('Poster area in cm squared:', width * height)

radius = float(input('Pond radius in m: '))
PI = 3.14159
print('Pond area in m squared:', PI * radius ** 2)

Output when the user types 60, 40, 2.5:

Poster width in cm: 60
Poster height in cm: 40
Poster area in cm squared: 2400
Pond radius in m: 2.5
Pond area in m squared: 19.6349375

The poster area multiplies width by height. The pond area uses exponentiation: radius ** 2 squares the radius, and Python works that out before multiplying by PI, because exponentiation has higher precedence than multiplication. So PI * radius ** 2 gives the right area, while (PI * radius) ** 2 would square the wrong thing. The power operator is always two asterisks, never ^.

celsius = float(input('Temperature in C: '))
fahrenheit = celsius * 9 / 5 + 32
print('Temperature in F:', fahrenheit)

price = float(input('Price before VAT: '))
vat_rate = 0.2
vat = price * vat_rate
print('Price with VAT:', price + vat)

Output when the user types 25, 40:

Temperature in C: 25
Temperature in F: 77.0
Price before VAT: 40
Price with VAT: 48.0

The temperature conversion multiplies by 9, divides by 5, then adds 32. Multiplication and division share the same precedence and run left to right, so celsius * 9 / 5 is worked out first and 32 is added to that result โ€” the same as writing (celsius * 9) / 5 + 32. The VAT program stores a fixed rate of 20% in vat_rate, calculates the VAT on the price, then adds it to the original price to get the total.

Text in, numbers out

Anything typed at input() arrives as text, even when it looks like a number, and '12' * 5 would repeat the text rather than multiply it. A typed value must be cast before it is used in a calculation: int() when it must be a whole number, such as a count of items, or float() when decimals are possible, such as a measurement or a price.

Never divide by zero

If the divisor of a division or a modulo is 0, Python cannot work out an answer and stops the program with an error. Sharing a bill between a number of people typed in by the user will fail if that number is 0, so the divisor must always hold a sensible value before the calculation runs.

Practise this