据我所知:
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 evaluatesx
; ifx
is false, its value is returned; otherwise,y
is evaluated and the resulting value is returned.The expression
x or y
first evaluatesx
; ifx
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/