Python reference
Floor division and modulo
Also called: // · % · remainder · divmod · wrap around
Definition
a // b divides and rounds down to the nearest whole number; a % b gives the remainder, so that a == (a // b) * b + a % b always holds.
Picture it
Floor division answers 'how many whole groups?', modulo answers 'how many left over?'. Modulo is perfect for wrapping: an index that goes past the end of a ring buffer, or a heading that must stay between 0 and 359 degrees. In Python, the remainder takes the sign of the divisor.
The maths
a = (a // b) × b + (a % b)
| Quantity | Unit | Symbol |
|---|---|---|
| ratio | dimensionless | 1 |
Worked example
What are 17 // 5, 17 % 5, -7 // 3 and -7 % 3 in Python?
- 17 = 3 × 5 + 2 → 3 and 2
- -7 / 3 = -2.33…, floor gives -3
- -7 = (-3) × 3 + 2 → remainder 2
Answer3, 2, -3 and 2.
✓ The 4 numbers in this answer are recomputed from scratch by an automated test.
In Python
heading = (350 + 30) % 360
print(heading) # 20
minutes, seconds = divmod(135, 60)
print(minutes, seconds) # 2 15Common misconceptions
- Misconception: -7 // 3 is -3 in Python, not -2: floor rounds down, towards minus infinity.
- Misconception: C, Java and JavaScript give -7 % 3 = -1; Python gives 2. Porting code between languages can break wrap-around logic.