Python divmod() function


The divmod() function in Python returns a tuple containing the quotient and the remainder when dividing two numbers. It performs both integer division (using //) and modulus (using %) in one operation.

Syntax

divmod(x, y)
  • x: The dividend (the number to be divided).
  • y: The divisor (the number by which x is divided).

Return Value

  • Returns a tuple (quotient, remainder), where:
    • quotient: The result of integer division (x // y).
    • remainder: The remainder of the division (x % y).

Examples

  1. Using divmod() with integers:

    print(divmod(10, 3)) # Output: (3, 1) # 10 // 3 = 3 (quotient), 10 % 3 = 1 (remainder)
  2. Using divmod() with negative numbers: The behavior follows the same rules of integer division and modulus for negative numbers.

    print(divmod(-10, 3)) # Output: (-4, 2) # -10 // 3 = -4 (quotient), -10 % 3 = 2 (remainder)
  3. Using divmod() with floating-point numbers: You can also use divmod() with floating-point numbers. The quotient is the result of floor division, and the remainder is the floating-point remainder.

    print(divmod(9.5, 2.5)) # Output: (3.0, 0.0) # 9.5 // 2.5 = 3.0 (quotient), 9.5 % 2.5 = 0.0 (remainder)
  4. Using divmod() in a loop: The function can be useful in breaking down numbers into quotient-remainder pairs in algorithms like time conversion.

    minutes = 130 hours, remainder = divmod(minutes, 60) print(hours, remainder) # Output: 2, 10 # 130 // 60 = 2 (hours), 130 % 60 = 10 (remainder minutes)

Benefits of divmod()

  • Efficiency: Since it performs both integer division and modulus in one step, it's faster and more efficient than calling x // y and x % y separately.
  • Convenience: It returns both the quotient and remainder at once, which is useful in many mathematical and algorithmic operations.

Summary

  • The divmod() function computes both the quotient and remainder of a division in a single operation.
  • It returns a tuple (quotient, remainder).
  • Works with integers and floating-point numbers, and is often used for tasks like time conversion, coin-counting algorithms, etc.