divmod()
The built-in divmod() function takes two numbers as arguments and returns a tuple containing the quotient and remainder from the integer division of the input numbers:
>>> divmod(8, 4)
(2, 0)
divmod() Signature
divmod(a, b)
Arguments
| Argument | Description |
|---|---|
a |
The dividend |
b |
The divisor |
Return Value
- With integers as arguments, it returns a tuple equivalent to
(a // b, a % b). - With floating-point numbers, it returns a tuple equivalent to
(q, a % b), whereqis usuallymath.floor(a / b), but it may be lower by1.
divmod() Examples
With integers as arguments:
>>> divmod(9, 4)
(2, 1)
With floating-point numbers as arguments:
>>> divmod(7.5, 2.5)
(3.0, 0.0)
divmod() Common Use Cases
The most common use cases for the divmod() function include:
- Calculating the quotient and remainder in a single operation.
- Converting time values into hours, minutes, and seconds.
- Distributing items evenly and finding the remainder.
divmod() Real-World Example
Suppose you need to convert a time value in milliseconds to a string formatted as "hh:mm:ss". You can achieve this using the divmod() function:
>>> def hh_mm_ss(milliseconds):
... seconds = round(milliseconds / 1000)
... minutes, seconds = divmod(seconds, 60)
... hours, minutes = divmod(minutes, 60)
... return f"{hours:02d}:{minutes:02d}:{seconds:02d}"
...
>>> hh_mm_ss(10000)
'00:00:10'
>>> hh_mm_ss(68000)
'00:01:08'
>>> hh_mm_ss(3680000)
'01:01:20'
In this example, divmod() helps you break down the time into hours, minutes, and seconds so that you can generate the desired output string.
Related Resources
Tutorial
Python Modulo Operator (%): How to Use Mod in Python
Learn how to use the Python modulo operator (%) for remainders, modular arithmetic, and more. Covers mod with ints, floats, and practical examples.
For additional information on related topics, take a look at the following resources:
- Numbers in Python (Tutorial)
- Python's Built-in Functions: A Complete Exploration (Tutorial)
- Python Modulo: Using the % Operator (Course)
- Python's Built-in Functions: A Complete Exploration (Quiz)