What is the difference between /, // and % in Python, especially with negative numbers?
/ is true division and always returns a float. // is floor division: it rounds down toward negative infinity. % returns the remainder that matches floor division, so the result takes the sign of the divisor. For example -7 // 2 is -4 and -7 % 2 is 1.
Explain it simply
Split 7 samosas between 2 friends. / tells you the exact share: 3.5. // tells you how many whole samosas each friend gets: 3. % tells you how many are left over: 1.
The surprise comes with negative numbers. Python's // always rounds down (toward negative infinity), not toward zero, and % is defined so that this rule always holds:
a == (a // b) * b + (a % b)Example
print(7 / 2) # 3.5
print(6 / 2) # 3.0 (still a float)
print(7 // 2) # 3
print(7 % 2) # 1
print(-7 // 2) # -4 (floor of -3.5 is -4, not -3)
print(-7 % 2) # 1 because (-4 * 2) + 1 == -7
print(7 % -2) # -1 the sign follows the divisor
print(divmod(17, 5)) # (3, 2)C, C++ and Java truncate toward zero, so in those languages -7 / 2 is -3 and -7 % 2 is -1. This difference often appears in interviews for people switching languages.
What to say in the interview
"/ is true division and gives a float. // floors toward negative infinity, and % gives a remainder with the sign of the divisor, so (a // b) * b + a % b == a always holds. That makes % n handy for wrap-around indexes, like going back one day from Monday with (day - 1) % 7."
Common mistakes
- Expecting
-7 // 2to be-3as in Java or C. - Using
int(a / b)for big integers; the float step can lose precision. Use//.