Get quotient and remainder with divmod() in Python

Modified: | Tags: Python, Numeric

In Python, you can easily compute the quotient using the // operator and the remainder using the % operator.

q = 10 // 3
mod = 10 % 3
print(q, mod)
# 3 1

If you need both the quotient and remainder, the built-in function divmod() is a convenient option.

divmod(a, b) returns a tuple containing the quotient and remainder as (a // b, a % b).

You can unpack the tuple and assign the values to individual variables.

q, mod = divmod(10, 3)
print(q, mod)
# 3 1

Alternatively, you can choose to work with the returned tuple directly.

answer = divmod(10, 3)
print(answer)
print(answer[0], answer[1])
# (3, 1)
# 3 1

Related Categories

Related Articles