Notes

`divmod()` Function in Python [ English ]

< Prev Next >

1. Introduction

The divmod() function in Python is a built-in function used to perform division and modulus operations at the same time. It returns a pair of numbers consisting of the quotient and the remainder.

In other words, the divmod() function combines the operations of integer division (//) and modulus (%) into a single function.

The result is returned as a tuple containing two values:

  1. Quotient
  2. Remainder

2. Syntax

divmod(a, b)

Parameters

  1. a The dividend (the number to be divided).

  2. b The divisor (the number by which the dividend is divided).

3. Return Value

The function returns a tuple containing two values:

[ (quotient, remainder) ]

Where:

4. Basic Example

print(divmod(10, 3))

Output

(3, 1)

Explanation

So the result is (3, 1).

5. Example with Variables

a = 20
b = 6

result = divmod(a, b)

print(result)

Output

(3, 2)

Explanation

6. Storing Quotient and Remainder Separately

q, r = divmod(15, 4)

print("Quotient:", q)
print("Remainder:", r)

Output

Quotient: 3
Remainder: 3

Explanation

7. Example with Floating-Point Numbers

print(divmod(9.5, 2))

Output

(4.0, 1.5)

Explanation

8. Equivalent Operations

The divmod() function is equivalent to performing two operations:

a = 10
b = 3

print(a // b)
print(a % b)

Output:

3
1

Using divmod():

print(divmod(10, 3))

Output:

(3, 1)

9. Practical Example

total_minutes = 130

hours, minutes = divmod(total_minutes, 60)

print("Hours:", hours)
print("Minutes:", minutes)

Output

Hours: 2
Minutes: 10

Explanation

10. Summary

< Prev Next >