+ 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='')
7 Antworten
+ 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.
+ 3
Always first AND, then OR. Understood.
+ 2
Yes, but WHY?
+ 2
And.... What's the rule? ☺️
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
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...
- 1
I'm giving up