0

precedence

Hi everyone, I really don't get this question from a python challenge: print(int(2/2*2-2+2%2)) The correct output is 0 But why? The precedence of multiplication is higher than division, so I supposed it must be calculate in this way: (2/(2*2))-(2+(2%2)) So, where is the error in my logic?

18th Mar 2022, 2:24 PM
David Lau
David Lau - avatar
5 ответов
+ 1
2/2 = 1 1*2 = 2 2 - 2 = 0 0 + (2%2) = 0 because: 2%2 = 0 The precedence of multiplication is not higher the division. You do them in the order they come. The correct way to add parentheses is: ((2/2)*2)-(2)+(2%2)
18th Mar 2022, 2:35 PM
Brain & Bones
Brain & Bones - avatar
+ 1
It is always relevent but the acronime PEMDAS helps you remember the rule, it is not the rule itself. It would probibly be better stated PE(M&D)(A&S) You do parenthese, exponets, multiplication and division (starting on the left), Addision and subtraction (also starting on the left)
18th Mar 2022, 3:08 PM
Brain & Bones
Brain & Bones - avatar
18th Mar 2022, 2:40 PM
David Lau
David Lau - avatar
0
No, if you read all of it, it clearifies “The associative operators are division, multiplication, remainder, etc. and the expressions will be evaluated from left to right.”
18th Mar 2022, 2:42 PM
Brain & Bones
Brain & Bones - avatar
0
But this doesn't explain to me why the order of PEMDAS is irrevelant. Or to ask from another direction: in which cases does the PEMDAS-rule has a meaning?
18th Mar 2022, 3:00 PM
David Lau
David Lau - avatar