Why `-7 % 3` Can Produce Two Answers

The percent sign looks familiar across Python, C, and JavaScript, but the operation’s result depends on how each language divides negative numbers. In Python, `-7 % 3` is `2`; in C and JavaScript, it is `-1`.

The difference comes from the quotient used to split a number into whole groups and a remainder. Python rounds division down: `-7 // 3` is `-3`, and the remainder is `2`, because `(-3 × 3) + 2 = -7`. C and JavaScript truncate the quotient toward zero, giving `-2`; the leftover is `-1`, because `(-2 × 3) + (-1) = -7`.

So the remainder keeps the sign of the divisor in Python, while in C and JavaScript it keeps the sign of the dividend—the number being divided. For positive inputs, these approaches usually agree, which is why the difference can go unnoticed until a value turns negative.

When the Difference Changes a Program

This matters whenever `%` is used to wrap a value into a repeating range: choosing a position in a circular list, mapping a number to a clock face, or cycling through animation frames. If a calculation produces `-1`, Python’s `-1 % 10` gives `9`, a valid position in a range from 0 to 9. C and JavaScript produce `-1`, which may be an invalid index or an unexpected state.

When a program needs a nonnegative result for a positive range size, the code should make that intention explicit. In JavaScript or C, a common normalization is `((x % n) + n) % n`, assuming `n` is positive. In Python, `x % n` already gives a result from `0` through `n - 1` for positive `n`.

The practical lesson is that `%` is not a portable promise of “wrap into a positive range.” A tiny negative input can change an array position, a loop’s phase, or a boundary condition when code moves between languages.