Let us assume we would like to divide 10 by 3. In Python we can do the following:

The output will be:

printing the result as a decimal. If we desire to find the quotient and remainder, we use specific operators for this purpose:

The output now will be:

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:

The output will be:

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.

Let us try using this dividing() function with a few inputs:

The output will be:

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:

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:

we get:

as expected. If we run:

the output will be:

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.

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!

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.