divmod()
Divides two numbers and returns both the whole-number result and the remainder as a pair, the same as (a // b, a % b).
divmod(a, b)divmod(a, b) does a division the way you learned it at school: how many times does b fit into a, and what is left over? It returns both answers together as a tuple, (quotient, remainder).
It is the neat way to split a total into units: seconds into minutes and seconds, cents into euros and cents, items into full boxes and leftovers. Unpack the pair straight into two names: minutes, seconds = divmod(200, 60).
With negative numbers the quotient is rounded down (towards minus infinity), so divmod(-7, 2) is (-4, 1), not (-3, -1). The remainder always has the same sign as b.
Parameters
| Parameter | What it is |
|---|---|
arequired | The number to divide (the dividend). |
brequired | The number to divide by (the divisor). It must not be zero. |
Return value
A tuple (a // b, a % b). With whole numbers both parts are int; if either input is a float, both are float.
Examples
1Quotient and remainder
print(divmod(17, 5))
q, r = divmod(17, 5)
print(q, "remainder", r)
print(5 * q + r)(3, 2) 3 remainder 2 17
5 * q + r always gives back the original number.
2Seconds into hours, minutes and seconds
total = 9876
minutes, seconds = divmod(total, 60)
hours, minutes = divmod(minutes, 60)
print(f"{hours}h {minutes:02d}m {seconds:02d}s")2h 44m 36s
3Pack items into boxes
eggs = 50
boxes, left = divmod(eggs, 12)
print(f"{boxes} full boxes and {left} eggs left over")4 full boxes and 2 eggs left over
4Cents into dollars and cents
for cents in [1999, 250, 7]:
dollars, rest = divmod(cents, 100)
print(f"${dollars}.{rest:02d}")$19.99 $2.50 $0.07
5Negative numbers and floats
print(divmod(-7, 2))
print(divmod(7, -2))
print(divmod(7.5, 2))(-4, 1) (-4, -1) (3.0, 1.5)
Common mistakes
Dividing by zero
divmod(x, 0) raises ZeroDivisionError. Check the divisor first when it comes from user data.
items, people = 10, 0
try:
print(divmod(items, people))
except ZeroDivisionError:
print("Cannot share between 0 people")Cannot share between 0 people
Expecting the remainder of a negative number to be negative
In Python -7 % 2 is 1, because the quotient is rounded down to -4. If you want the result rounded towards zero, as in some other languages, use math.fmod() for the remainder and int(a / b) for the quotient.
Questions people ask
What is the difference between divmod() and // and %?
None in the result: divmod(a, b) equals (a // b, a % b). It is just shorter when you need both, and does one division instead of two.
How do I convert minutes to hours and minutes?
hours, minutes = divmod(total_minutes, 60).
Does divmod() work with floats?
Yes, but floats are not exact: divmod(0.3, 0.1) gives (2.0, 0.09999999999999998). For money, work in whole cents or use the decimal module.