布尔 Python 值混淆

2022-01-19 00:00:00 python python-2.7 boolean

问题描述

我是 Python 新手,在尝试 Python 逻辑语句时.我遇到了这个我无法理解的问题.谁能告诉我 Python 2.7 中发生了什么.Python 中 0 和 False 值有什么区别.

<上一页>>>> 0 或假错误的>>> 错误或 00

为什么口译员给出不同的答案?

解决方案

你被 or 操作符的行为弄糊涂了;它返回第一个表达式,仅当它是 true 值时;0False 都不为真,因此返回第二个值:

>>>0 或酒吧"'酒吧'>>>错误或富"富"

任何不是数字 0、空容器、NoneFalse 的值都被认为是 true(自定义类可以通过实现 __bool__ 方法 (python 3)、__nonzero__ (python 2) 或 __len__(长度 0 为空).

如果第一个表达式为 True,则甚至不计算第二个表达式:

>>>真或 1/0真的

1/0 表达式会引发 ZeroDivision 异常,但 Python 甚至不会对其进行评估.

布尔运算符文档中记录了这一点:

<块引用>

表达式x or y首先计算x;如果 x 为真,则返回其值;否则,评估 y 并返回结果值.

同样,and如果为False则返回第一个表达式,否则返回第二个表达式.

I'm new to Python and while trying Python logical statements.I came across this which I'm not able to understand.Can anyone tell me whats happening here in Python 2.7.Whats the difference between 0 and False value in Python.

>>> 0 or False
False
>>> False or 0
0

Why the interpreter is giving different answers ?

解决方案

You are being confused by the behaviour of the or operator; it returns the first expression that only if it is a true value; neither 0 nor False is true so the second value is returned:

>>> 0 or 'bar'
'bar'
>>> False or 'foo'
'foo'

Any value that is not numerical 0, an empty container, None or False is considered true (custom classes can alter that by implementing a __bool__ method (python 3), __nonzero__ (python 2) or __len__ (length 0 is empty).

The second expression is not even evaluated if the first is True:

>>> True or 1 / 0
True

The 1 / 0 expression would raise a ZeroDivision exception, but is not even evaluated by Python.

This is documented in the boolean operators documentation:

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.

Similarly, and returns the first expression if it is False, otherwise the second expression is returned.

相关文章