Yandex

Python divmod() Function – Quotient and Remainder in One Go



Python divmod() Function

The divmod() function in Python returns a tuple containing the quotient and the remainder when dividing two numbers. It's a quick way to get both results in one line.

Syntax

divmod(a, b)

Parameters:

  • a – The dividend (numerator)
  • b – The divisor (denominator); must not be 0

Returns:

  • A tuple (quotient, remainder)

Example 1: Integer Division

result = divmod(10, 3)
print(result)
(3, 1)

Why? Because 10 ÷ 3 = 3 with a remainder of 1.

Example 2: Assigning Quotient and Remainder

q, r = divmod(22, 5)
print("Quotient:", q)
print("Remainder:", r)
Quotient: 4
Remainder: 2

Example 3: Using with Floats

print(divmod(7.5, 2.5))
(3.0, 0.0)

Use Cases

  • Efficiently calculate both quotient and remainder in a single step
  • Common in loops where both values are needed
  • Useful in modular arithmetic problems

Common Mistakes

  • Passing 0 as the second argument will raise ZeroDivisionError
  • Both arguments must be numeric (int or float)

Interview Tip

In coding interviews, divmod() can simplify logic in problems involving floor division and modulo operations.

Summary

  • divmod(a, b) returns (a // b, a % b)
  • Works with both integers and floats
  • Returns a tuple with two elements: quotient and remainder

Practice Problem

Write a program that reads two integers from the user and prints their quotient and remainder using divmod().

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
q, r = divmod(a, b)
print("Quotient:", q)
print("Remainder:", r)


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M