Like the documentation says in Binary arithmetic operations, Python assures that:
The integer division and modulo operators are connected by the following identity: x == (x/y)*y + (x%y)
. Integer division and modulo are also connected with the built-in function divmod(): divmod(x, y) == (x/y, x%y)
.
And truly,
>>> divmod(-2, 5)
(-1, 3).
Another way to visualize the uniformity of this method is to calculate divmod
for a small sequence of numbers:
>>> for number in xrange(-10, 10):
... print divmod(number, 5)
...
(-2, 0)
(-2, 1)
(-2, 2)
(-2, 3)
(-2, 4)
(-1, 0)
(-1, 1)
(-1, 2)
(-1, 3)
(-1, 4)
(0, 0)
(0, 1)
(0, 2)
(0, 3)
(0, 4)
(1, 0)
(1, 1)
(1, 2)
(1, 3)
(1, 4)