据我所知:
and、or 是 boolean 运算符,任何 boolean 表达式都应返回一个 boolean 值。
那么,为什么会发生这种情况:
False or 'name'返回'name'而不是TrueTrue 和 ''返回''而不是False
请解释一下,python 是如何处理 boolean 表达式的?
请您参考如下方法:
不,在 python 中,or 和 and 操作短路并返回最后计算的项目。
参见 Boolean operations :
The expression
x and yfirst evaluatesx; ifxis false, its value is returned; otherwise,yis evaluated and the resulting value is returned.The expression
x or yfirst evaluatesx; ifxis true, its value is returned; otherwise,yis evaluated and the resulting value is returned.
如果您必须有一个 boolean 值,使用bool() :
>>> bool(False or 'name')
True
