The divmod()
function returns both the quotient and remainder when dividing two numbers. This is useful for math calculations, loops, and handling division efficiently.
Example
result = divmod(10, 3)
print(result) # Output: (3, 1)
Here, 10 ÷ 3
gives:
- Quotient →
3
- Remainder →
1
Syntax
divmod(a, b)
- a → Dividend (number to be divided).
- b → Divisor (number to divide by).
- Returns → A tuple
(quotient, remainder)
.
This is the same as using:
quotient = a // b
remainder = a % b
1. Using divmod()
in a Loop
When distributing items, divmod()
helps track full sets and leftovers.
total_candies = 20
kids = 6
q, r = divmod(total_candies, kids)
print(f"Each kid gets {q} candies, {r} left over.")
# Output: Each kid gets 3 candies, 2 left over.
2. Using divmod()
with Time Conversion
Convert seconds into minutes and remaining seconds.
seconds = 125
minutes, remaining_seconds = divmod(seconds, 60)
print(f"{minutes} minutes and {remaining_seconds} seconds")
# Output: 2 minutes and 5 seconds
Perfect for countdowns, timers, and scheduling.
3. Using divmod()
for Large Number Operations
For big calculations, divmod()
is faster than using //
and %
separately.
num = 123456789
divisor = 10000
quotient, remainder = divmod(num, divisor)
print(f"Quotient: {quotient}, Remainder: {remainder}")
# Output: Quotient: 12345, Remainder: 6789
Key Notes
- ✔ Returns both quotient and remainder – faster than using
//
and%
separately. - ✔ Great for distributing items and tracking leftovers.
- ✔ Useful for time conversions – seconds to minutes, hours to days.
- ✔ Efficient for handling large numbers in math-heavy applications.
By using divmod()
, you can simplify division-based calculations, making your code faster and cleaner. 🚀