Boolean Python Value confusion(布尔 Python 值混淆)
问题描述
我是 Python 新手,在尝试 Python 逻辑语句时.我遇到了这个我无法理解的问题.谁能告诉我 Python 2.7 中发生了什么.Python 中 0 和 False 值有什么区别.
<上一页>>>> 0 或假错误的>>> 错误或 00为什么口译员给出不同的答案?
你被 or 操作符的行为弄糊涂了;它返回第一个表达式,仅当它是 true 值时;0 和 False 都不为真,因此返回第二个值:
>>>0 或酒吧"'酒吧'>>>错误或富"富"任何不是数字 0、空容器、None 或 False 的值都被认为是 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 yfirst evaluatesx; ifxis true, its value is returned; otherwise,yis evaluated and the resulting value is returned.
Similarly, and returns the first expression if it is False, otherwise the second expression is returned.
这篇关于布尔 Python 值混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:布尔 Python 值混淆
基础教程推荐
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
