Get the quotient and remainder of a division at the same time using Python’s divmod

Money and Business

In Python, you can use “\” to calculate the quotient of an integer and “%” to calculate the remainder (remainder, mod).

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

The built-in function divmod() is useful when you want both the quotient and remainder of an integer.

The following tuples are returned by divmod(a, b).
(a // b, a % b)

Each can be unpacked and acquired.

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

Of course, you can also pick it up directly at the tuple.

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