python - Python 中的基本 bool 表达式产生令人惊讶的结果

标签 python python-3.x boolean-expression

在 Python 中,我有 2>3 == False这给 False .但我期待 True .如果我使用括号,即 (2>3) == False然后我收到 True .这背后的理论是什么?

最佳答案

这是因为 Python 的一个特性与其他编程语言相比非常不寻常,即您可以在一个序列中编写两个或多个比较,它具有数学家直观的含义。例如,像 0 < 5 < 10 这样的表达式是 True因为 0 < 5 and 5 < 10True .

From the docs :

Comparisons can be chained arbitrarily; for example, 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).



所以,表达式 2 > 3 == False相当于 2 > 3 and 3 == False , 即 False .

关于python - Python 中的基本 bool 表达式产生令人惊讶的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59278084/

相关文章:

python - 如何在Python中获取在线视频文件的视频时长?

python - 我如何使用带有大量分隔符的 pandas 转换 csv

python - 高斯曲率和平均曲率适用于粗糙表面吗?

python - 没有 html 标签时的 HTML 抓取

javascript - "true"即使值为假,评估仍在运行

python - 如何从 PySpark 的 SQLite 数据库文件加载表?

python - IDLE 无法导入 Tkinter。你的 Python 可能没有为 Tk 配置

python - 尝试在 PostgresQL SELECT 中使用 Python 变量时的语法问题

ios - 无法正确执行方法调用

java - 如何创建一个 boolean 局部变量作为 MouseEvent 的结果?