为什么 (1 == 2 != 3) 在 Python 中评估为 False? [英] Why does (1 == 2 != 3) evaluate to False in Python?

查看:87
本文介绍了为什么 (1 == 2 != 3) 在 Python 中评估为 False?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么 (1 == 2 != 3) 在 Python 中的计算结果为 False,而 ((1 == 2) != 3)(1 == (2 != 3)) 计算结果为 True?

这里使用了什么运算符优先级?

解决方案

这是由于操作符 连锁现象.Pydoc 将其解释为:

<块引用>

比较可以任意链接,例如 x <;y <= z 是等价的x ,除了 y 只计算一次(但在两个当 x <; 时根本不评估情况 zy 被发现是假的).

如果您查看 优先级code>== 和 != 运算符,您会注意到它们具有相同的优先级,因此适用于链接现象.

所以基本上会发生什么:

<预><代码>>>>1==2=>错误的>>>2!=3=>真的>>>(1==2) 和 (2!=3)# 假与真=>错误的

Why does (1 == 2 != 3) evaluate to False in Python, while both ((1 == 2) != 3) and (1 == (2 != 3)) evaluate to True?

What operator precedence is used here?

解决方案

This is due to the operators chaining phenomenon. The Pydoc explains it as :

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

And if you look at the precedence of the == and != operators, you will notice that they have the same precedence and hence applicable to the chaining phenomenon.

So basically what happens :

>>>  1==2
=> False
>>> 2!=3
=> True

>>> (1==2) and (2!=3)
  # False and True
=> False

这篇关于为什么 (1 == 2 != 3) 在 Python 中评估为 False?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆