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
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 包装空间模型 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
