# Problems with negative numbers as operands in a calculation using modulus operator

I am familiar with this operation in Python 3.6:

​>>>​​ ​​17​​ ​​//​​ ​​10​
​ 1
The following is a bit tricky but its understandable as long as we remember that python will take the floor of the result of the integer division

​>>>​​ ​​-17​​ ​​//​​ ​​10​
​ -2

But how do you explain this?:

-17%10
3

and

17 % -10
-3

Sometimes best explained by looking at the mathematical relationship:
For any two non-zero numbers a and b:
(b * (a // b) + a % b) is equal to a
And memorizing the rule that “When using modulo, the sign of the result matches the sign of the divisor (the second operand)”.
Hope that helps. I’ve had to put it on flashcards and now it’s ‘up there’ to stay, I hope.

3 Likes

Well, it works.

(b * (a//b) + a % b) = a

if a = -17 and b = 10
then
(10 * (-2) + a % b) = -17
so a % b = 3

if a = 17 and b = -10
(-10 * (-2) + a % b ) = 17
or a % b = -3

But i now have to remember this formula to do the calculation.

Awesome response @LaurelVW.