The Python divmod() function allows us a way to easily get the quotient and remainder after division of two numbers.

print(divmod(15,4))

#Output:
(3, 3) 

When performing different calculations with numbers in Python, the ability to easily get certain pieces of information about the calculation can be useful.

One such case is when dividing by two numbers in Python. We can easily get the quotient and remainder after division in Python.

To get the quotient and remainder after division of two numbers in Python, the easiest way is with the Python divmod() function.

The Python divmod() function takes two arguments – the two numbers you want to divide, and returns a tuple with the first element being the quotient and the second element being the remainder.

Below is an example showing you how to use divmod() to get a quotient and remainder from two numbers in Python.

print(divmod(15,4))
print(divmod(20,6))
print(divmod(10,3))
print(divmod(19,5))

#Output:
(3, 3) 
(3, 2) 
(3, 1) 
(3, 4) 

You can then verify these are the correct values by multiplying the first returned element by the second parameter and adding the second returned element.

res = divmod(15,4)

print(res[0] * 4 + res[1])

#Output:
15

Calculating Quotient and Remainder with Float Inputs to divmod() in Python

The Python divmod() function allows float inputs as well as integer inputs. You will still get the quotient and remainder from the two floating point numbers in the same way as the integer inputs.

Below are a few examples showing how to find the quotient and remainder after division of two floats with divmod() in Python.

print(divmod(15.5,4.1))
print(divmod(20.3,9.2))
print(divmod(1.3,0.3))
print(divmod(5.4,0.5))

#Output:
(3.0, 3.200000000000001)
(2.0, 1.9000000000000021)
(4.0, 0.10000000000000009)
(10.0, 0.40000000000000036) 

Hopefully this article has been useful for you to learn how to use the divmod() function in Python.

Categorized in:

Python,

Last Update: March 22, 2024