Understanding Python Modulo Operator(%) in Python
The modulo operator % in Python is one of those operators that can be surprisingly tricky, especially when negative numbers are involved. if you’ve ever wondered why -7 % 3 gives 2 instead of -1. This article will break it down in simple terms.
What is the modulo operator?
The modulo operator returns the remainder of a division.
moduloPositive = 7 % 3 #modulo with positive numbers
print(moduloPositive) # Output: 1Modulo with Negative Numbers
This is where Python behaves differently from some other languages.
moduloNegative = -7 % 3 #modulo with a negative number
print(moduloNegative) # Output: 2You might expect -1 because -7 ÷ 3 = -2 remainder -1. But Python actually gives 2.
Why?
In Python, the result of the modulo operation has the same sign as the divisor (the second operand), not the dividend.
The Fundamental Formula:
Get Ravi’s stories in your inbox
Join Medium for free to get updates from this writer.
In Python, the modulo operator is mathematically linked to the floor division operator (//) by the following identity.
r = a — (b * (a // b))
where:
a = -7
b = 3
Calculate Floor Division:
First, we find the result of -7 // 3. As we discussed in the previous article https://medium.com/@ravinerusu06/understanding-floor-division-in-python-985e790fdbb8 , floor division rounds toward negative infinity.
-7 / 3 = -2.333… So floor value is -7 // 3 = -3
Now substitute values into the formula to find r:
r = -7 — (3 * -3)
r = -7 — (-9)
r = -7 + 9
r = 2
Conclusion:
The result of -7 % 3 is 2, because Python calculates the remainder based on floor division (-7//3 = -3), which results in the formula -7-(3*-3) = 2.
#Python #Programming #Coding #Developers






