【发布时间】:2019-07-01 16:20:09
【问题描述】:
在解释器中弄乱了值和概念并遇到了一个逻辑绊脚石,因为 4
【问题讨论】:
标签: python-3.x comparison operators
在解释器中弄乱了值和概念并遇到了一个逻辑绊脚石,因为 4
【问题讨论】:
标签: python-3.x comparison operators
>>> 4<5
True
>>> 4<5 == True
False
>>> (4<5) == True
True
>>>
我希望这能消除您的疑虑。 4<5 == True 评估为 4<5 and 5 == True 总体返回 False,因为 4<5 为 True,但 5 == True 为 False。这是因为< 和== 具有相同的优先级。
【讨论】:
来自 Python documentation
形式上,如果 a, b, c, ..., y, z 是表达式,并且 op1, op2, ..., opN 是 比较运算符,则 a op1 b op2 c ... y opN z 等价于 a op1 b 和 b op2 c 和 ... y opN z,除了每个表达式是 最多评估一次。
根据本规范,4 < 5 == True 等于 4 < 5 and 5 == True(在 Python 中,operator precedence 等于 (4 < 5) and (5 == True)),其中 4 < 5 是 True,但 5 == True 是 False。所以True and False 是False。
【讨论】:
在 Python3 中:4 < 5 == True 等价于 4 < 5 and 5 == True,其计算结果为 False,因为 5 != True。
注意< 和== 具有相同的优先级。
文档供参考https://docs.python.org/3/reference/expressions.html#comparisons
【讨论】: