How should I interpret this sentence in Python (in terms of operators precedence)?
c = not a == 7 and b == 7
as c = not (a == 7 and b == 7) or c = (not a) == 7 and b == 7?
thanks
How should I interpret this sentence in Python (in terms of operators precedence)?
c = not a == 7 and b == 7
as c = not (a == 7 and b == 7) or c = (not a) == 7 and b == 7?
thanks
Using dis module:
>>> import dis
>>> def func():
... c = not a == 7 and b == 7
...
>>> dis.dis(func)
2 0 LOAD_GLOBAL 0 (a)
3 LOAD_CONST 1 (7)
6 COMPARE_OP 2 (==)
9 UNARY_NOT
10 JUMP_IF_FALSE_OR_POP 22
13 LOAD_GLOBAL 1 (b)
16 LOAD_CONST 1 (7)
19 COMPARE_OP 2 (==)
>> 22 STORE_FAST 0 (c)
25 LOAD_CONST 0 (None)
28 RETURN_VALUE
So, it looks like:
c = (not(a == 7)) and (b == 7)
According to the documentation the order is, from lowest precedence (least binding) to highest precedence (most binding):
andnot==So the expression not a == 7 and b == 7 will be evaluated like this:
((not (a == 7)) and (b == 7))
^ ^ ^ ^
second first third first
In other words, the evaluation tree will look like this:
and
/ \
not ==
| / \
== b 7
/ \
a 7
And the last thing done will be the assignment of the expression's value to c.
(not(a == 7)) and (b == 7). If it were highest to lowest, as you say, then it would be ((not a) == (7 and b)) == 7, since and would be higher precedence than the ==.