我是 Python 的新手,在尝试 Python 逻辑语句时遇到了这个我无法理解的问题。谁能告诉我 Python 2.7 中发生了什么。Python 中 0 和 False 值之间有什么区别.
>>> 0 or False False >>> False or 0 0
为什么口译员给出不同的答案?
最佳答案
您对 或
运算符的行为感到困惑;它返回第一个表达式,只有当它是一个 true 值时; 0
和 False
都不为真,因此返回第二个值:
>>> 0 or 'bar'
'bar'
>>> False or 'foo'
'foo'
任何不是数字 0、空容器、None
或 False
的值都被视为 true(自定义类可以通过实现 __bool__
方法(python 3)、__nonzero__
(python 2)或__len__
(长度 0 为空)。
如果第一个表达式为 True
,则甚至不会计算第二个表达式:
>>> True or 1 / 0
True
1/0
表达式会引发一个 ZeroDivision
异常,但甚至不会被 Python 求值。
这记录在 boolean operators documentation 中:
The expression
x or y
first evaluatesx
; ifx
is true, its value is returned; otherwise,y
is evaluated and the resulting value is returned.
类似地,and
如果为False
则返回第一个表达式,否则返回第二个表达式。
关于python - Boolean Python 值混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19778268/