1

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

1

2 Answers 2

5

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)
Sign up to request clarification or add additional context in comments.

Comments

2

According to the documentation the order is, from lowest precedence (least binding) to highest precedence (most binding):

  1. and
  2. not
  3. ==

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.

2 Comments

The link you give says that the list is ordered lowest precedence to highest precedence, so it would be (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 ==.
@EricFinn yup, my mistake - fixed it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.