+ 2
please can you explain me the outcome? how does it come to be -3 and 3. I am really confused.
print ((-12)%5) print ((-12)//5)
3 Réponses
+ 2
% is the ‘modulo’ (or remainder) operator in Python. In this example, it finds the highest multiple of 5 less than -12, which is -15, and gives the difference between the two (i.e. 3). Note that this means that no answer from the modulo operator can be negative.
// also finds the greatest multiple of 5 less than -12 (again, -15) but it divides it by 5, hence you get -3 as the answer. Note that the // operator will always return an integer.
When working with positive numbers, a//b returns the number of times that b goes wholly into a, and a%b returns the remainder when a is divided by b.
+ 1
thank you. One more question. could you explain this:
print (5%(-12))
print (5//(-12))
+ 1
Ok, so it turns out that the output always has the same sign (positive or negative) as the denominator. (This was news to me.)
So, when the second number is negative, both will find the lowest multiple of that number greater than the other (so the lowest multiple of -12 greater than 5 is 12). % then returns the difference (-7) and // tells you how many times -12 goes into 12 (-1).