Arithmetic operators
You have already used +, -, * and /. Python has three more arithmetic operators. Here they all are:
| Operator | What it does | Example | Result |
|---|---|---|---|
+ |
addition | 7 + 2 |
9 |
- |
subtraction | 7 - 2.5 |
4.5 |
* |
multiplication | -3 * 4 |
-12 |
/ |
division | 7 / 2 |
3.5 |
// |
integer division (rounds down) | 7 // 2 |
3 |
% |
remainder, also called modulo | 7 % 2 |
1 |
** |
power | 2 ** 3 |
8 |
Integer division and the remainder
// divides and rounds the result down to a whole number: it tells you how many times one number fits into another. % gives what is left over. Together they answer questions such as "how many full boxes, and how many items left":
>>> 17 // 5
3
>>> 17 % 5
25 fits into 17 three times, which makes 15, and 2 is left over. Here the same idea turns minutes into hours and minutes:
minutes = 135
hours = minutes // 60
rest = minutes % 60
print(f"{minutes} minutes is {hours} h {rest} min.")
135 minutes is 2 h 15 min.The remainder is also a quick test for even numbers: an even number divided by 2 leaves nothing, so 14 % 2 is 0, while 15 % 2 is 1. That comes in handy with the conditions at the end of this part.
Powers
** raises a number to a power: 2 ** 3 is 2 * 2 * 2.
>>> 2 ** 3
8
>>> 5 ** 2
25
>>> 10 ** 6
1000000Watch out: in Python, ^ is not a power. It's a different operator that this course doesn't need, so 2 ^ 3 gives a wrong answer without any error message:
>>> 2 ^ 3
1