facha - 4 months ago 34

Python Question

I've found some strange behaviour in python regarding negative numbers:

`>>> a = -5`

>>> a % 4

3

Could anyone explain what's going on?

Answer

Unlike C or C++, Python's modulo operator (`%`

) always return a number having the same sign as the denominator (divisor). Your expression yields 3 because

(-5) % 4 = (-2 × 4 + 3) % 4 = 3.

It is chosen over the C behavior because a nonnegative result is often more useful. An example is to compute week days. If today is Tuesday (day #2), what is the week day *N* days before? In Python we can compute with

```
return (2 - N) % 7
```

but in C, if *N* ≥ 3, we get a negative number which is an invalid number, and we need to manually fix it up by adding 7:

```
int result = (2 - N) % 7;
return result < 0 ? result + 7 : result;
```

(See http://en.wikipedia.org/wiki/Modulo_operator for how the sign of result is determined for different languages.)