Python 3 reference · Built-in Functions
Python divmod() Function
Divide two numbers and return the quotient and the remainder together as a tuple: (a // b, a % b).
Python 3 Since 3.0
Syntax
divmod(a, b)
Parameters
| Parameter | Description |
|---|---|
a |
The dividend. |
b |
The divisor (not zero). |
Return value
A tuple (quotient, remainder).
Examples
print(divmod(17, 5))
print(divmod(-17, 5)) # the remainder takes the divisor's sign
Output
(3, 2) (-4, 3)
seconds = 3725
minutes, secs = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
print(f"{hours}h {minutes}m {secs}s")
Output
1h 2m 5s
items, per_page = 47, 10
pages, rest = divmod(items, per_page)
print(pages + (1 if rest else 0), "pages")
Output
5 pages
Good to know
With negative numbers Python's // rounds down (toward negative infinity), so divmod(-17, 5) is
(-4, 3), not (-3, -2) as in C or Java.
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
abs()· Return the absolute value of a number: its distance from zero, so negative numbers become positive.pow()· Raise a number to a power, like base ** exp. With a third argument it computes the result modulo a number efficiently.round()· Round a number to a given number of decimal places. Halfway values round to the nearest even number (banker's rounding).- Python Operators · tutorial
- Python Math · tutorial