← Intro to programming with Python

Doing math

Add, subtract, multiply and divide, in the right order.

Start this lesson

Python is a very patient calculator. It uses + and - as usual, * for multiply and / for divide. It follows the same order as math class: multiplication and division happen before addition and subtraction, and anything in parentheses happens first. This matters because 3 + 4 * 2 is 11, not 14, and a program that gets the order wrong gives wrong answers without any warning.

print(3 + 4 * 2)     # 11
print((3 + 4) * 2)   # 14
print(10 / 4)        # 2.5
print(10 / 2)        # 5.0

Division with / always gives a decimal number, even when it comes out even, so 10 / 2 shows 5.0.

Common mistake: the average of 80 and 90 is (80 + 90) / 2. Without the parentheses, 80 + 90 / 2 divides only the 90 and gives 125.

Use * for multiply, not x or ×.

Numbers inside quotes are text. "5" + 3 gives a TypeError, because Python will not add text to a number.