问题描述
我是 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 值混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)