Doing Math
Add, subtract, multiply, divide and more
Python is a brilliant calculator. Here are the symbols (called operators) you'll use most:
+add-subtract*multiply (a star, not the letter x)/divide
print(10 + 4)
print(10 - 4)
print(10 * 4)
print(10 / 4)That last one, 10 / 4, gives 2.5 — a number with a decimal point (a float). Division in Python always gives a decimal result, even when it divides evenly.
Two more handy operators
**means "to the power of".2 ** 3is 2 × 2 × 2 =8.%(called modulo) gives the remainder after dividing.10 % 3is1, because 3 goes into 10 three times with 1 left over.
Order matters
Python follows the same order of operations you learned in school: multiplication and division happen before addition and subtraction. Use round brackets to force a different order:
print(2 + 3 * 4) # 14, because 3*4 happens first
print((2 + 3) * 4) # 20, brackets go firstMath with variables
You can do math with variables, not just raw numbers:
price = 8
quantity = 3
total = price * quantity
print("Total:", total)Tip: Use brackets whenever you're unsure of the order. They're free, and they make your intent obvious to anyone reading.
Your turn
Change the price and quantity and watch the total update.
Press “Run code” to see the result.
Quick check
Q1 What is the result of 2 + 3 * 4 in Python?
Q2 What does the % operator give you, as in 10 % 3 ?
Want to save your progress? It's free.
Create a free account