Python divmod()

Python divmod() function is handy for performing division and getting both the quotient (result of the division) and the remainder (leftover part) in one go. It’s like doing two calculations at once, saving you a step when you need both pieces of information.

divmod() Syntax

quotient, remainder = divmod(dividend, divisor)
  • quotient, remainder: Variables to store the calculated quotient and remainder.
  • divmod(): The built-in Python function that performs the division and returns the results as a tuple.
  • dividend: The number being divided.
  • divisor: The number you’re dividing by.

Example 1: Python divmod()

result = divmod(10, 3)
print(result)  # Output: (3, 1)

Code Explanation

  • Line 1: Divides 10 by 3, storing the quotient (3) and remainder (1) in the result tuple.
  • Line 2: Prints the tuple containing both results.

Output

(3, 1)


Example 2: Python divmod() with Integer Arguments

quotient, remainder = divmod(20, 7)
print(f"Quotient: {quotient}, Remainder: {remainder}")  # Output: Quotient: 2, Remainder: 6

Shows divmod() with integers, clearly showing the quotient and remainder.

Output

Quotient: 2, Remainder: 6


Example 3: Python divmod() with Float Arguments

quotient, remainder = divmod(15.5, 4)
print(f"Quotient: {quotient}, Remainder: {remainder}")  # Output: Quotient: 3.0, Remainder: 3.5

Shows how divmod() handles floating-point numbers, producing a float quotient and remainder.

Output

Quotient: 3.0, Remainder: 3.5


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

try:
    result = divmod("hello", 3) 
except TypeError:
    print("TypeError: unsupported operand type(s) for divmod(): 'str' and 'int'")

Illustrates that divmod() expects numeric arguments. Using a string triggers a TypeError.


Example 5: Converting Seconds to Minutes and Seconds

total_seconds = 135
minutes, seconds = divmod(total_seconds, 60)
print(f"{minutes} minutes and {seconds} seconds")  # Output: 2 minutes and 15 seconds

Code Explanation

  • Line 1: Sets the total number of seconds.
  • Line 2: Calculates minutes and remaining seconds using divmod().
  • Line 3: Formats and prints the result in a user-friendly way.

Output

2 minutes and 15 seconds


Also Read

Python dir()

Python enumerate()