Python3 divmod() Function
The Python divmod() function accepts two numeric (non-complex) parameters and returns a tuple (a // b, a % b) containing the quotient and remainder.
In Python 3.x, this function does not support complex numbers.
Function Syntax
The divmod() function accepts two parameters, usually two numbers, and returns a tuple containing two values. The first value is the quotient (i.e., the integer part) of the first parameter divided by the second parameter, and the second value is the remainder.
divmod(a, b)
Parameter Description:
- a: Number, not complex.
- b: Number, not complex.
If both parameters a and b are integers, the result returned by the function is equivalent to(a // b, a % b)。
If one of the parameters is a float, the result returned by the function is equivalent to (q, a % b), where q is usually math.floor(a / b), but may also be 1 less than that. However, the value of q * b + a % b will be very close to a.
If the result of a % b is not 0, the sign of the remainder is the same as that of parameter b. If b is positive, the remainder is positive; if b is negative, the remainder is also negative, and 0 <= abs(a % b) < abs(b).
Example
(3, 1)
>>> divmod(8, 2)
(4, 0)
>>> divmod(8, -2)
(-4, 0)
>>> divmod(3, 1.3)
(2.0, 0.3999999999999999)
Application Scenarios of divmod() Function
divmod() is very useful in scenarios such as time conversion and pagination calculation.
1. Time conversion. For example, convert total seconds to hours, minutes, and seconds:
Example
hours, remainder = divmod(total_seconds, 3600)
minutes, seconds = divmod(remainder, 60)
print(f{hours} hours {minutes} minutes {seconds} seconds) # Output: 1 hour 1 minute 1 second
2. Pagination calculation. In a pagination system, divmod() can be used to calculate the total number of pages and the number of records on the last page:
Example
items_per_page = 10
pages, remainder = divmod(total_items, items_per_page)
if remainder:
pages += 1
print(fTotal pages: {pages}) # Output: Total pages: 11
Precautions for divmod() Function
The second parameter of the divmod() function cannot be 0, otherwise it will raise a ZeroDivisionError exception.
The types of the quotient and remainder returned by the divmod() function depend on the types of the input parameters. If the input parameters are integers, the returned quotient and remainder are also integers; if the input parameters are floats, the returned quotient and remainder are also floats.
Other Extensions
Python3 Built-in Functions