Python divmod()

The divmod() method takes two numbers as arguments and returns their quotient and remainder in a tuple.

Example

# returns the quotient and remainder of 8/3 result = divmod(8, 3)
print('Quotient and Remainder = ',result) # Output: Quotient and Remainder = (2, 2)

divmod() Syntax

The syntax of divmod() is:

divmod(number1, number2)

divmod() Parameters

The divmod() method takes in two parameters:

  • number1 - numerator, can be an integer or a floating point number
  • number2 - denominator, can be an integer or a floating point number

divmod() Return Value

The divmod() method returns:

  • (quotient, remainder) - a tuple that contains quotient and remainder of the division
  • TypeError - for any non-numeric argument

Example 1: Python divmod() with Integer Arguments

# divmod() with integer arguments
print('divmod(8, 3) = ', divmod(8, 3))

# divmod() with integer arguments
print('divmod(3, 8) = ', divmod(3, 8))

# divmod() with integer arguments
print('divmod(5, 5) = ', divmod(5, 5))

Output

divmod(8, 3) =  (2, 2)
divmod(3, 8) =  (0, 3)
divmod(5, 5) =  (1, 0)

Here, we have used the divmod() method with integer arguments

  • divmod (8,3) - computes quotient and remainder of 8/3 - results in (2, 2)
  • divmod (3,8) - computes quotient and remainder of 3/8 - results in (0, 3)
  • divmod (5,5) - computes quotient and remainder of 5/5 - results in (1, 0)

Example 2: Python divmod() with Float Arguments

# divmod() with float arguments
print('divmod(8.0, 3) = ', divmod(8.0, 3))

# divmod() with float arguments
print('divmod(3, 8.0) = ', divmod(3, 8.0))

# divmod() with float arguments
print('divmod(7.5, 2.5) = ', divmod(7.5, 2.5))

# divmod() with float arguments
print('divmod(2.6, 0.5) = ', divmod(2.6, 0.5))

Output

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)

In the above example, we have used the divmod() method with the floating point numbers. That's why we get both the quotient and the remainder as decimal.


Example 3: Python divmod() with Non-Numeric Arguments

# divmod() with string arguments a = divmod("Jeff", "Bezos")
print('The divmod of Jeff and Bezos is = ', a)

Output:

TypeError: unsupported operand type(s) for divmod()

In the program above, we have used string arguments, "Jeff" and "Bezos" with divmod().

Hence, we get TypeError: unsupported operand type(s) for divmod() as output.


Recommended Readings:

Did you find this article helpful?