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
-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
res = -5 % -4
Comment if you have any doubts or suggestions on this Python modulo topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.