Kodeclik Blog
Python's divmod() function
Let us assume we would like to divide 10 by 3. In Python we can do the following:
print(10/3)
The output will be:
3.3333333333333335
printing the result as a decimal. If we desire to find the quotient and remainder, we use specific operators for this purpose:
print(10/3)
print(10 // 3)
print(10 % 3)
The output now will be:
3.3333333333333335
3
1
Note that the “//” operator computes the quotient and the “%” operator computes the remainder.
The divmod() function simply computes both in the same statement and thus returns two values, the quotient and remainder in a tuple. Here is how that works:
print(divmod(10,3))
The output will be:
(3, 1)
where the first element of the tuple is the quotient and the second element is the remainder.
A user-friendly divmod() function
Here is a wrapper function dividing that pretty prints the output of the divmod() function.
def dividing(x,y):
(a,b) = divmod(x,y)
print(str(x) + " divided by "
+ str(y) + " gives "
+ "a quotient of "
+ str(a) + " and a remainder of "
+ str(b))
Let us try using this dividing() function with a few inputs:
dividing(10,2)
dividing(10,3)
dividing(100,3.0)
The output will be:
10 divided by 2 gives a quotient of 5 and a remainder of 0
10 divided by 3 gives a quotient of 3 and a remainder of 1
100 divided by 3.0 gives a quotient of 33.0 and a remainder of 1.0
As shown here, for the last line, because one of the inputs is a float, the outputs will also be floating point numbers.
Converting proper fractions into mixed fractions in Python
We can use the divmod() function to convert a fraction into a mixed fraction. Here is how that might work:
def convert_fraction(num, den):
(quo, rem) = divmod(num,den)
print(str(num)+"/"+str(den)
+ " = "
+ str(quo) + " "
+ str(rem) + "/" + str(den))
In this function (which takes “num”, the numerator, and “den”, the denominator as inputs), we first use the divmod() function to find the quotient and remainder in the variables “quo” and “rem”. Then we pretty print the output as a mixed fraction.
If we run this as:
convert_fraction(17,10)
we get:
17/10 = 1 7/10
as expected. If we run:
convert_fraction(7,10)
the output will be:
7/10 = 0 7/10
So, to summarize, the Python divmod() function is a built-in function that takes two numbers as arguments and returns a pair of numbers consisting of their quotient and remainder.
For similar Python + math content, checkout the math.ceil() and math.floor() functions! Also
learn about the math domain error in Python and how to fix it!
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.