+ 2

Python - Logical operators evaluation order

Why these results? Especially, why is c 1? a = 0 and 1 or 0 b = 0 and 0 or 1 c = 1 or 0 and 0 d = 0 or 1 and 0 print(a,b,c,d,sep='')

11th Sep 2019, 11:07 AM
Paolo De Nictolis
Paolo De Nictolis - avatar
7 Respuestas
+ 4
Boolean operators from lowest precedence to highest precedence: OR, AND, NOT. https://docs.python.org/3/reference/expressions.html#operator-precedence Therefore, the expressions are evaluated as: a = (0 and 1) or 0 # 0 or 0 == 0. b = (0 and 0) or 1 # 0 or 1 == 1. c = 1 or (0 and 0) # 1 or 0 == 1. d = 0 or (1 and 0) # 0 and 0 == 0.
11th Sep 2019, 12:54 PM
Diego
Diego - avatar
+ 3
Always first AND, then OR. Understood.
11th Sep 2019, 1:02 PM
Paolo De Nictolis
Paolo De Nictolis - avatar
+ 2
Yes, but WHY?
11th Sep 2019, 11:25 AM
Paolo De Nictolis
Paolo De Nictolis - avatar
+ 2
And.... What's the rule? ☺️
11th Sep 2019, 11:39 AM
Paolo De Nictolis
Paolo De Nictolis - avatar
0
a = 0 and 1 or 0 b = 0 and 0 or 1 c = 1 or 0 and 0 d = 0 or 1 and 0 print(a,b,c,d,sep='') #0110
11th Sep 2019, 11:24 AM
Anton Böhler
Anton Böhler - avatar
0
they are probably executed in this order: a = 0 and (1 or 0) b = (0 and 0) or 1 c = 1 or (0 and 0) d = (0 or 1) and 0 print(a,b,c,d,sep='') it really is weird, but by placing brackets you can make it the order is right...
11th Sep 2019, 11:34 AM
Anton Böhler
Anton Böhler - avatar
- 1
I'm giving up
30th Sep 2019, 3:35 PM
James
James - avatar