在 Python 中,我有 2>3 == False
这给 False
.但我期待 True
.如果我使用括号,即 (2>3) == False
然后我收到 True
.这背后的理论是什么?
最佳答案
这是因为 Python 的一个特性与其他编程语言相比非常不寻常,即您可以在一个序列中编写两个或多个比较,它具有数学家直观的含义。例如,像 0 < 5 < 10
这样的表达式是 True
因为 0 < 5 and 5 < 10
是 True
.
From the docs :
Comparisons can be chained arbitrarily; for example,
x < y <= z
is equivalent tox < y and y <= z
, except thaty
is evaluated only once (but in both casesz
is not evaluated at all whenx < y
is found to be false).
所以,表达式
2 > 3 == False
相当于 2 > 3 and 3 == False
, 即 False
.
关于python - Python 中的基本 bool 表达式产生令人惊讶的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59278084/