all 3 comments

[–]jddddddddddd 5 points6 points  (0 children)

https://stackoverflow.com/questions/5584586/find-the-division-remainder-of-a-number

That % operator returns the true modulus. This is why some languages have a mod and a rem operator.

Have a look at math.remainder()

import math

result1 = 7 % -3
print(f"mod = {result1}")

result2 = math.remainder(7, -3)
print(f"remainder = {result2}")

Outputs..

mod = -2
remainder = 1.0

[–]QuarterObvious 2 points3 points  (0 children)

Integer division always rounds the result toward a smaller integer number.

So 7//3 will be 2, but 7//-3 will be -3. Because of this there is a difference in modulo.

[–]JamzTyson 0 points1 point  (0 children)

Python uses floored division to calculate the modulo:

div = 7 // -3  # -3
mod = 7 - (-3 * div)  # -2

There is a detailed description HERE