Doing Maths in Python

The maths operators

OperatorNameExampleResult
+add7 + 29
-subtract7 - 25
*multiply7 * 214
/divide7 / 23.5
//whole-number divide7 // 23
%remainder (modulo)7 % 21
**power7 ** 249
print(7 + 2)
print(7 - 2)
print(7 * 2)
print(7 / 2)
print(7 // 2)
print(7 % 2)
print(7 ** 2)

Output

9
5
14
3.5
3
1
49

Normal division always gives a float

print(10 / 2)

Output

5.0

Even though 10 divides exactly by 2, / gives 5.0. If you want a whole number, use //.

// and % – sharing sweets

Think of it like this: You have 17 sweets and 5 friends. Each friend gets 17 // 5 = 3 sweets, and 17 % 5 = 2 sweets are left over.

sweets = 17
friends = 5
print("Each friend gets", sweets // friends)
print("Left over:", sweets % friends)

Output

Each friend gets 3
Left over: 2

Tip: % is great for checking if a number is even: number % 2 is 0 for even numbers and 1 for odd numbers.

Rounding

round() rounds a number. Give it a second number to keep that many decimal places:

price = 19.4567
print(round(price))
print(round(price, 2))

Output

19
19.46

Common mistake: Dividing by zero crashes your program with a ZeroDivisionError. You'll learn how to handle that in module 10.

HOME LEARN COMMUNITY DASHBOARD