python : Why does False or 'name' returns 'name' and not False?

标签 python boolean boolean-logic boolean-expression boolean-operations

据我所知:

andor 是 boolean 运算符,任何 boolean 表达式都应返回一个 boolean 值。

那么,为什么会发生这种情况:

  • False or 'name' 返回 'name' 而不是 True
  • True 和 '' 返回 '' 而不是 False

请解释一下,python 是如何处理 boolean 表达式的?

最佳答案

不,在 python 中,orand 操作短路并返回最后计算的项目。

参见 Boolean operations :

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

如果您必须有一个 boolean 值,使用bool() :

>>> bool(False or 'name')
True

关于 python : Why does False or 'name' returns 'name' and not False?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13137061/

相关文章:

python - 将行从一个文件复制到另一个文件

javascript - boolean 测试 HTML 文本框输入与数组值的比较

c - 为什么在 stdbool.h 中使用整数而不是无符号整数?

assembly - 不能使用 CPU12 处理器

python - 为什么 Z3 对于微小的搜索空间很慢?

c++ - C++11 或 C++14 是否支持三值或多值逻辑?

python - 为什么有时会打印 "Correct!"两次并且不接受输入?

python - 如何使用 Python 滚动到 Selenium 中元素可见的页面位置?

python - 虾 4 : 400 ERROR when trying to download a users comments

java - boolean 分支语句