note.nkmk.me

Get quotient and remainder with divmod() in Python

Posted: 2019-09-16 / Tags: Python

In Python, you can calculate the quotient with // and the remainder with %.

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 the remainder.

divmod(a, b) returns a tuple (a // b, a % b).

Each can be assigned to a variable using unpacking.

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

Of course, you can receive it as a tuple.

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

Related Categories

Related Posts