The modulo in Python is confusing.
In Python, %
operator is calculating the remainder:
>>> 9 % 5
4
However:>
In integers, you can't always pick such a quotient that quotient * divisor == dividend
. If the product
does not equal the dividend
, one always has to make a choice, whether to make it slightly less than the dividend
, or slightly greater than the dividend
. The sum of the product
with the remainder
makes the dividend
, that's what the remainder
is. In any case, the dividends and products have to be close, meaning the absolute value of the remainder has to be less than that of the divisor.
When the divisor
is positive, the products
increase as the quotients
increase; when the divisor
is negative, the products
decrease as the quotients
increase. In the first case, the products go from the below, in the second case, the products go from the above. In Python, in both cases the next quotient
is only taken when the dividend
reaches the next possible product
, going the same way the products go. Before that, only the remainder
changes to accommodate for the next dividend
, again always going in the same direction as the dividends change, without a break at zero. This rule is universal in Python, it holds always.
That is not the reason why this choice had been made, but that gives the idea what happens (i. e. why the results are what they are, and which results to expect).