The maths operators
| Operator | Name | Example | Result |
|---|---|---|---|
+ | add | 7 + 2 | 9 |
- | subtract | 7 - 2 | 5 |
* | multiply | 7 * 2 | 14 |
/ | divide | 7 / 2 | 3.5 |
// | whole-number divide | 7 // 2 | 3 |
% | remainder (modulo) | 7 % 2 | 1 |
** | power | 7 ** 2 | 49 |
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 = 3sweets, and17 % 5 = 2sweets 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 % 2is0for even numbers and1for 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.