Skip to main content
 首页 » 编程设计

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

2025年05月04日12powertoolsteam

据我所知:

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

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

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

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

请您参考如下方法:

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

参见 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