Sub topic 3
Division, floor division and modulo
This chapter assumes you know how to run Python code, that you know int and float, and that you have read the earlier chapters on expressions and arithmetic operators. It covers three operators that people often treat as one: /, // and %. It shows how they relate, what happens with negative numbers and floats, and where each one fits.
Three operators, one identity
Python has three division-related operators and one built-in that combines two of them.
| Operator | Name | Result type for two ints |
|---|---|---|
| `a / b` | True division | Always `float` |
| `a // b` | Floor division | `int` |
| `a % b` | Modulo (remainder) | `int` |
| `divmod(a, b)` | Both at once | Tuple `(a // b, a % b)` |
The three are tied together by one rule that Python guarantees for ints and floats:
a == (a // b) * b + a % b// picks the whole-number quotient, and % is whatever is left over so that the equation holds. Once you accept that rule, the behaviour with negative numbers follows from the definition of //.
True division always returns a float
/ never returns an int, even when the division is exact.
print(7 / 2)
print(6 / 3)
print(7 // 2)
print(-7 // 2)
print(7.5 // 2)
print(-7 % 2)
print(7 % -2)
print(-7 % -2)
print(divmod(-7, 2))The output is:
3.5
2.0
3
-4
3.0
1
-1
-1
(-4, 1)6 / 3 gives 2.0, not 2. If you need an integer result, use //. If an int is required, for example as a list index, passing 6 / 3 raises a TypeError.
Floor division rounds toward negative infinity
// returns the largest whole number that is less than or equal to the true quotient. For positive numbers this looks like "drop the decimals". For negative quotients it does not: -7 / 2 is -3.5, and the floor of -3.5 is -4, not -3.
If either operand is a float, // returns a float that holds a whole number, so 7.5 // 2 is 3.0.
Modulo takes the sign of the divisor
With the identity above, -7 % 2 must satisfy -7 == (-4) * 2 + r, so r is 1. In general, the result of % is zero or has the same sign as the right operand. For a positive divisor b, the result always lies in 0 <= r < b.
| a | b | a // b | a % b |
|---|---|---|---|
| 7 | 2 | 3 | 1 |
| -7 | 2 | -4 | 1 |
| 7 | -2 | -4 | -1 |
| -7 | -2 | 3 | -1 |
This differs from C, Java and JavaScript, where % takes the sign of the dividend. If you need that behaviour, use math.fmod for floats, or truncate explicitly:
import math
print(int(-7 / 2))
print(math.trunc(-7 / 2))
print(math.fmod(-7, 2))This prints -3, -3 and -1.0. Note that math.fmod always returns a float.
Why the floor convention is useful
Because a % b stays in 0 <= r < b for positive b, it works for wrap-around logic even when a is negative.
days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
start = 5
print(days[(start + 4) % 7])
print(days[(0 - 1) % 7])This prints Wed and then Sun. Stepping back one day from Monday lands on index 6, because -1 % 7 is 6. A truncating remainder would give -1, which happens to index the last item here but would break in languages without negative indexing.
divmod is useful when you need both parts and want to do the division only once:
total_seconds = 3725
minutes, seconds = divmod(total_seconds, 60)
hours, minutes = divmod(minutes, 60)
print(f"{hours}h {minutes}m {seconds}s")This prints 1h 2m 5s.
Choosing an operator
Division by zero
All three operators raise ZeroDivisionError when the right operand is zero, for ints and for floats. Unlike some languages, Python does not return inf or nan for 1.0 / 0.
for op in (lambda: 1 / 0, lambda: 1 // 0, lambda: 1 % 0, lambda: 1.0 / 0):
try:
op()
except ZeroDivisionError:
print("ZeroDivisionError")The loop prints ZeroDivisionError four times. Validate the divisor before dividing, or catch the exception where you can recover from it.
Floats make `//` and `%` surprising
// and % on floats are computed from the stored binary values, not from the decimal literals you typed. Since 0.1 is stored as a number slightly larger than one tenth, 1 // 0.1 does not give 10.0.
from decimal import Decimal
print(1 // 0.1)
print(1 % 0.1)
print(divmod(1, 0.1))
print(Decimal("1") // Decimal("0.1"))
print(Decimal("-7") % Decimal("2"))The output is:
9.0
0.09999999999999995
(9.0, 0.09999999999999995)
10
-1Note the last line of the output. Decimal uses the truncating convention for %, so Decimal("-7") % Decimal("2") is -1, unlike the int result of 1. Do not assume that every numeric type follows the int rule.
Large integers stay exact
Ints in Python have no fixed size, so // and % are exact for them. True division converts to a float and loses precision for large values.
n = 10**20
print(n // 3)
print(int(n / 3))The first line prints 33333333333333333333. The second prints a different number, because n / 3 is a float with about 15 to 17 significant digits. When you need a whole-number quotient of large ints, always use //, not int(a / b).
Common mistakes
- Writing
a / bwhere a whole number is needed, then getting aTypeErrorwhen using the result as an index or inrange. - Expecting
-7 // 2to be-3. It is-4. - Expecting
-7 % 2to be-1. It is1. - Using
%on floats for exactness checks. - Forgetting that the identity
a == (a // b) * b + a % bholds, and re-deriving results by hand instead of checking withdivmod.
Exercise
Without running the code, what do -17 // 5, -17 % 5, 17 // -5 and 17 % -5 evaluate to? Check your answers against the identity a == (a // b) * b + a % b.
Show answer
-17 // 5 is -4 (the floor of -3.4), and -17 % 5 is 3, because -4 5 + 3 = -17. 17 // -5 is -4 (the floor of -3.4), and 17 % -5 is -3, because -4 -5 + -3 = 17.
Exercise
A video is 7384 seconds long. Write code that uses divmod to print its length as hours, minutes and seconds in the form 2h 3m 4s.
Show answer
hours, rest = divmod(7384, 3600) gives (2, 184). minutes, seconds = divmod(rest, 60) gives (3, 4). So print(f"{hours}h {minutes}m {seconds}s") prints 2h 3m 4s.