[Tutor] modulo

Oscar Benjamin oscar.j.benjamin at gmail.com
Mon Oct 8 01:16:57 CEST 2012

On 8 October 2012 00:07, Dave Angel <d at davea.name> wrote:
> On 10/07/2012 06:49 PM, Esteban Izaguirre wrote:
>> Hi, I'm following coursera's learn to program: the fundamentals, which
>> teaches programming basics in python. Our first assignement involves the
>> modulo operator with a negative divident, and while I've managed to get to
>> understand it enough for the purposes of the assignement with help from
>> othe rstudents, I still don't know how the hell it works, I wouldn't know
>> how to use modulo in another situation if it ever arised. So, i undertand
>> how modulo works when only positive numbers are used, but how does modulo
>> determine, that, say -15 % 14 is equal to 13? Or -20 % 100 is 20? I just
>> don't get how modulo works, all explanations I've found online only seem to
>> be in relation of how this applies to perl or something, can someone
>> explain it to me?
> There is one perfectly reasonable definition for how modulo should
> behave if the denominator (modulus) is positive. Python does it 'right',
> so I'll try to explain it in a couple of ways.
> (If the modulus (denominator) is negative, it makes no sense to me, so I
> can't even recall what Python does, and I have to look it up each time.
> Fortunately this is rare, and in my code, I just avoid it)

The sign of the modulo operation is always the same as the sign of the

>>> 3%5
>>> 3%(-5)
>>> (-3)%5
>>> (-3)%(-5)

That way you can say that the result of the a % b is always in the
range from 0 to b (not including b itself).


More information about the Tutor mailing list