Sub topic 3
Division, floor division and modulo
This chapter assumes you know basic Python syntax, the built-in types int and float, and simple assignment. You can run the examples in a script or the REPL.
Three operators, one relationship
Python has three division-related operators:
/is true division. It always returns afloat, even when the result is whole (6 / 3gives2.0).//is floor division. It rounds the result down toward negative infinity.%is modulo. It returns the remainder that goes with//.
print(7 / 2)
print(7 // 2)
print(-7 // 2)
print(-7 % 2)
print(divmod(-7, 2))
print(2 ** 10)The output is 3.5, 3, -4, 1, (-4, 1) and 1024.
The result of -7 // 2 surprises many learners. The exact quotient is -3.5. Flooring rounds down to -4, not toward zero to -3.
The rule that ties them together
For any integers a and b (with b not zero), Python guarantees this:
a == (a // b) * b + a % bCheck it with -7 and 2: (-4) * 2 + 1 is -7. The remainder is whatever makes the equation true after the quotient is floored. This means the sign of % follows the divisor, not the dividend.
print(7 % -2)
print(7 // -2)
print(-7 % -2)This prints -1, -4 and -1. When the divisor is positive, the remainder is always in the range 0 up to (but not including) the divisor. That makes % reliable for wrap-around logic.
Practical uses
Use divmod when you need both values. It computes them in one call.
total_seconds = 3725
minutes, seconds = divmod(total_seconds, 60)
hours, minutes = divmod(minutes, 60)
print(hours, minutes, seconds)This prints 1 2 5.
Modulo also handles cyclic positions, such as a clock or a circular list. Because the result follows the divisor's sign, negative steps still land in range.
print((10 + 5) % 12)
print((0 - 1) % 5)This prints 3 and 4.
Common errors
- Truncating instead of flooring.
int(-7 / 2)gives-3, but-7 // 2gives-4. Do not treat them as interchangeable for negative values. - Expecting an
intfrom//. Floor division with a float operand returns a float.7.5 // 2is3.0. - Dividing by zero.
/,//and%all raiseZeroDivisionErrorwhen the right operand is zero. - Using
/for counts.10 / 2is5.0, which fails when you need an integer index. Use//.
Exercise
What do -9 // 4 and -9 % 4 evaluate to, and what equation confirms they agree?
Show answer
-9 // 4 is -3, because -2.25 floors down to -3. -9 % 4 is 3. The check is (-3) * 4 + 3 == -9, which is true.
Exercise
Write one line using divmod that splits 500 cents into dollars and remaining cents.
Show answer
dollars, cents = divmod(500, 100) gives dollars == 5 and cents == 0.