Skip to content

Python modulo negative numbers

  • by

Python’s modulo operator (%) always return a number having the same sign as the denominator (divisor). So Python modulo negative numbers will be a positive number if the denominator positive number.

Python applies the distribute law of the Modulo operator which is:

(a+b)mod n = [(a mod n)+(b mod n)]mod n

Math calculation

-5%4 = (-2*4 + 3) % 4 = 3

Python modulo negative numbers example

Simple example code using negative modulo.

res1 = -5 % 4
res2 = ((-2 * 4) + 3) % 4

print(res1)
print(res2)

res = -5 % -4
print(res)

Output:

Python modulo negative numbers

Comment if you have any doubts or suggestions on this Python modulo topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading