Integer division¶

The Python division operator that we've seen up to now always produces a float:

In [1]:
5/3

Out[1]:
1.6666666666666667
In [2]:
5/5

Out[2]:
1.0

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.

In [3]:
14//3

Out[3]:
4
In [4]:
13//3

Out[4]:
4
In [5]:
456//5

Out[5]:
91
In [6]:
15//5

Out[6]:
3

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.

In [7]:
(-16)//5

Out[7]:
-4
In [8]:
int(-16/5)

Out[8]:
-3

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:

In [9]:
a, b = -42, 5

In [10]:
(a//b) * b + (a % b)

Out[10]:
-42

Which is what we'd expect with positive numbers as well.