In this article, I'll cover Python's "divmod function". The "divmod function" is a convenient way to get the quotient and remainder when dividing. Let's deepen our knowledge of Python by becoming able to use the "divmod" function.
In normal division in Python, use "/" to find the quotient and "%" to find the remainder.
#quotient
12 / 4
>>>3.0
#quotient
12 / 5
>>>2.4
#Truncate the decimal point
12 // 5
>>>2
#remainder
12 % 4
>>> 0
#remainder
12 % 5
>>> 2
Now, let's use the "divmod function" immediately. Let's check the code first.
quotient, remainder = divmod(12, 5)
print(quotient) #2
print(remainder) #2
As you can see, we have two variables, the first variable contains the quotient and the second variable contains the remainder. And the point is that the first variable contains the "quotient with the decimal point truncated". In other words, it is the same as when using "//".
Next, let's check what happens when we receive it with one variable.
tuple = divmod(12, 5)
print(tuple) #(2, 2)
You can receive it as a tuple like this. When you want to take it out
print(tuple[0], tuple[1])
#2 2
Then you can take it out.
Finally, let's compare the normal quotient and remainder when using the "divmod function".
#usually
quotient = 12 / 5
remainder = 12 % 5
print(quotient) #2.4
print(remainder) #2
#divmod function
quotient, remainder = divmod(12 / 5)
print(quotient) #2
print(remainder) #2
It's only one line, but you can see that it's shortened. If even one line gets shorter, there is no reason not to use it, so let's use it positively.
In this article, I covered Python's "divmod function". We will continue to write articles about useful modules and built-in functions, so please take a look if you like.
Recommended Posts