Python Modulo Why Is 1-4 %5 Not The Same As (1-4)%5
Does anyone know why the code below does not have the same outcome in Python? Why do I need the parenthesis to get the correct outcome? #example 1 print 1-4 %5 outcome: -3 #exampl
Solution 1:
This is due to operator precedence. Mod (%
) takes precedence over -
, so:
1-4 % 5 == 1 - (4 % 5) == 1 - 4 == -3
but
(1-4) % 5 == -3 % 5 == 2
Solution 2:
Python operator precedence has minus just lower than modulus
http://www.mathcs.emory.edu/~valerie/courses/fall10/155/resources/op_precedence.html
*, /, % Multiplication, division, remainder
+, - Addition, subtraction
Post a Comment for "Python Modulo Why Is 1-4 %5 Not The Same As (1-4)%5"