Python makes maths straightforward with operators. You already know
+ for addition. Here are its siblings: - subtracts, * multiplies, and / divides. These symbols work exactly as you expect from school.print(10 + 5)
print(10 - 3)
print(4 * 2)
print(9 / 2)Look closely at the last line.
9 / 2 gives you 4.5. In Python, / always returns a float (a number with decimals), even if the result looks like a whole number. This behaviour is consistent and predictable.Sometimes you want only the whole part of a division or the leftover remainder. Use
// for integer division and % for modulo. Integer division rounds down to the whole number below, so 7 // 2 is 3. Modulo gives you what is left over after making full groups.# 7 // 2: how many full groups of 2 in 7?
print(7 // 2)
# 7 % 2: what is left over after making those groups?
print(7 % 2)You will use
// when packing items into boxes. For example, if you have 17 items and boxes hold 6, integer division tells you how many full boxes fit. You can also use % to check parity: if a number divided by 2 has no remainder, it is even.Exponentiation
The
** operator raises a number to a power. For example, 2 ** 3 means three twos multiplied together: 2 * 2 * 2, which is 8. It reads as "two to the third".print(5 ** 2)
print(10 ** 1)Order of Operations
Python follows the usual maths rules. Multiplication and division happen before addition and subtraction, just like in school. If you need to change this order, use parentheses
().# Python does multiplication first: (3 * 4) + 2
print(2 + 3 * 4)
# Parentheses force addition first: (2 + 3) * 4
print((2 + 3) * 4)Converting and Rounding
You can switch between integers (
int) and floats using int() and float(). Use round() to clean up messy decimals. This is useful when you need a whole number for display. One surprise: a number exactly halfway goes to the nearest even whole number, so round(2.5) is 2, but round(3.5) is 4.# Convert float to int (cuts off the decimal)
print(int(9.8))
# Round to the nearest whole number
print(round(1.567))