Python divmod() function in Linux

The divmod() function is used to divide and return the result as an integer and the remainder of the two entered numbers. What this function does is to take two numbers and returns a pair of numbers (a tuple) consisting of their quotient and remainder. This is a common math operation in python to help solve math problems.

Here at LinuxAPT, as part of our Server Management Services, we regularly help our Customers to perform related Python function queries.

In this context, we shall look into how to use the divmod() function in Python.


More about divmod() function and it's syntax 

The divmod() function returns 2 values: integer and remainder. 

Basically, divmod() returns:

(q, r) - a pair of numbers (a tuple) consisting of quotient q and remainder r

If x and y are integers, the return value from divmod() is same as (a // b, x % y).

If either x or y is a float, the result is (q, x%y). Here, q is the whole part of the quotient.

It's syntax is given below:

divmod(x, y)

It's Parameter Values is given below:

  • x: dividend also known as a non-complex number (numerator).
  • y: divisor also regarded as a non-complex number (denominator).


Examples of using Python divmod() function

1. If you have a fuctions such as:

x = divmod(7, 2)
print(x)

The output will be:

(3, 1)


2. Take a look at another divmod() fuction:

x = divmod(9, 4)
y = divmod(7, 2)
print("x = ", x)
print("y = ", y)

The output will be:

x = (2, 1)
y = (3, 1)


3. Here is another one:

divmod() combines input() function
print("Enter x number:")
x = int(input())
print("Enter y number:")
y = int(input())
z = divmod(x, y)
print("Result: ",z)

The Output will be:

Enter x number: 5
Enter y number: 2
Result: (2, 1)


4. A complex divmod() fuction is given below:

print('divmod(8, 3) = ', divmod(8, 3))
print('divmod(3, 8) = ', divmod(3, 8))
print('divmod(5, 5) = ', divmod(5, 5))
# divmod() with Floats
print('divmod(8.0, 3) = ', divmod(8.0, 3))
print('divmod(3, 8.0) = ', divmod(3, 8.0))
print('divmod(7.5, 2.5) = ', divmod(7.5, 2.5))
print('divmod(2.6, 0.5) = ', divmod(2.6, 0.5))

It's Output would be:

divmod(8, 3) =  (2, 2)
divmod(3, 8) =  (0, 3)
divmod(5, 5) =  (1, 0)
divmod(8.0, 3) =  (2.0, 2.0)
divmod(3, 8.0) =  (0.0, 3.0)
divmod(7.5, 2.5) =  (3.0, 0.0)
divmod(2.6, 0.5) =  (5.0, 0.10000000000000009)


[Need to fix any Python function issues ? We are here. ]

This article covers how to use the divmod() function in Python. In fact, Python divmod() function is employed to return a tuple that contains the value of the quotient and therefore the remainder when dividend is divided by the divisor. It takes two parameters where the first one is the dividend and the second one is the divisor.


Python divmod() function Parameter Values:

  • divident - This parameter contains the number you want to divide.
  • divisor - This parameter contains the number you want to divide with.

Related Posts