我正在学习《笨办法学Python》(LPTHW),在其中遇到了一些我无法理解的内容。什么时候会出现这样的情况,即你想让布尔运算符and
或者or
返回除布尔值以外的其他值呢?LPTHW的文本指出,像Python这样的所有语言都有这种行为。他是指编译型语言还是解释型语言,还是鸭子类型和静态类型语言?
我运行了下面的代码:
>>> False and 1
False
>>> True and 1
1
>>> 1 and False
False
>>> 1 and True
True
>>> True and 121
121
>>> False or 1
1
>>> False or 112
112
>>> False or "Khadijah"
'Khadijah'
>>> True and 'Khadijah'
'Khadijah'
>>> False or 'b'
'b'
>>> b = (1, 2, "K")
>>> b
(1, 2, 'K')
>>> False or b
(1, 2, 'K')
>>>
请帮我理解这里发生了什么。根据文档:http://docs.python.org/2/library/stdtypes.html 具有布尔结果的操作和内置函数总是针对 false 返回
0
或 False
,针对 true 返回 1
或 True
,除非另有说明。(重要的例外情况:布尔运算符 or
和 and
总是返回它们的一个操作数。)根据 LPTHW:http://learnpythonthehardway.org/book/ex28.html 为什么
"test" and "test"
返回 "test" 或者1 and 1
返回 1 而不是 True?
Python 和许多类似的语言返回其布尔表达式中的一个操作数,而不仅仅是 True 或 False。这意味着如果你执行 False and 1,你会得到第一个操作数(False)但如果你执行 True and 1,你会得到第二个操作数(1)。尝试一下。
and
操作将在找到第一个False操作数时停止评估操作数。or
操作将在找到第一个True操作数时停止评估操作数。 - wwiiand
操作将返回最后一个操作数。or
操作将返回第一个评估为True的操作数。这里有使用案例 - 记住这一点,总有一天你会恍然大悟! - wwii