Python operators precedence

好久不见. 提交于 2021-02-02 09:37:20

问题


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:


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)



回答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.



来源:https://stackoverflow.com/questions/19009898/python-operators-precedence

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!