TutreNews Learn

First steps

Arithmetic

Goal: Use Python's arithmetic operators correctly · 8 min

operatormeaningexampleresult
+ − *add, subtract, multiply7 * 321
/division (always float)7 / 23.5
//integer (floor) division7 // 23
%remainder (modulo)7 % 21
**power2 ** 532

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

  1. 200 seconds // 60 = 3 full minutes.
  2. 200 % 60 = 20 seconds left over.
  3. Output: 3 min 20 s
s = 200
print(s // 60, "min", s % 60, "s")

Output:

3 min 20 s