The Python division operator that we've seen up to now always produces a float
:
5/3
5/5
Sometimes, we might be interested in integer division -- the division operation you might be familiar with from elementary school, where the result is always an integer (and there is a remainder, which you can always compute separately.) We use //
for that in Python.
14//3
13//3
456//5
15//5
Note that the result is always an int
.
Side note: it's not the case that int(a/b) == a//b
, because of negative numbers.
(-16)//5
int(-16/5)
It's not really worth bothering with the rules for dividing (by) negative integers -- just convert everything to its absolute value, and then add the sign if this situation comes up. We can, however, check the following:
a, b = -42, 5
(a//b) * b + (a % b)
Which is what we'd expect with positive numbers as well.