Arithmetic Operators and Precedence
This is a free course. Log in to run the code exercises and track your progress.
Arithmetic Operators and Precedence
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | addition | 7 + 2 | 9 |
- | subtraction | 7 - 2 | 5 |
* | multiplication | 7 * 2 | 14 |
/ | division (always a float) | 7 / 2 | 3.5 |
// | floor division | 7 // 2 | 3 |
% | remainder (modulus) | 7 % 2 | 1 |
** | exponent (power) | 7 ** 2 | 49 |
Precedence decides which operator is applied first: **, then * / // %, then + -. Operators of the same level work left to right. Brackets always come first.
print(2 + 3 * 4) # 14, not 20
print((2 + 3) * 4) # 20
print(2 ** 3 ** 2) # 512: ** works right to left
minutes = 135
print(minutes // 60, minutes % 60) # 2 15
Read a number of minutes and print it as hours and minutes, exactly like 2 hours 5 minutes. Use // and %.
total = int(input())
hours = 0 # whole hours in total
minutes = 0 # minutes left over
print(hours, "hours", minutes, "minutes")Log in to edit and run this code.