First steps
Arithmetic
Goal: Use Python's arithmetic operators correctly · 8 min
| operator | meaning | example | result |
|---|---|---|---|
| + − * | add, subtract, multiply | 7 * 3 | 21 |
| / | division (always float) | 7 / 2 | 3.5 |
| // | integer (floor) division | 7 // 2 | 3 |
| % | remainder (modulo) | 7 % 2 | 1 |
| ** | power | 2 ** 5 | 32 |
Precedence follows maths: ** before * / // % before + −; use brackets to be explicit.
% is surprisingly useful: n % 2 == 0 tests for even numbers, seconds % 60 gives the leftover seconds. Shortcuts: x += 5 means x = x + 5.
Worked example: Minutes and seconds
- 200 seconds // 60 = 3 full minutes.
- 200 % 60 = 20 seconds left over.
- Output:
3 min 20 s
s = 200
print(s // 60, "min", s % 60, "s")Output:
3 min 20 s