Comparison operators' priority in Python vs C/C++

不羁的心 提交于 2019-12-10 13:56:26

问题


In C/C++, comparison operators such as < > have higher priority than == does. This code will evaluate to true or 1:

if(3<4 == 2<3) {  //3<4 == 2<3 will evaluate to true
    ...
}

But in Python, it seems wrong:

3<4 == 2<3  #this will evaluate to False in Python.

In Python, does every comparison operator have the same priority?


回答1:


In Python, not only do comparison operators gave the same priority, they are treated specially (they chain rather than group). From the documentation:

Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... and y opN z, except that each expression is evaluated at most once.

In your case, the expression

3<4 == 2<3

is equivalent to

3 < 4 and 4 == 2 and 2 < 3

which is False due to the second clause.




回答2:


Short answer: yeah, all the comparisons have the same precedence

Long answer: you may want to have a look on the documentation: Precedence on Python



来源:https://stackoverflow.com/questions/8802864/comparison-operators-priority-in-python-vs-c-c

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