一直以来,我以为python中and和or的返回值是True或False。
看 《Dive into Python》这本书时,发现他们并不返回布尔值,而是返回他们实际进行比较的值之一。
and
根据自己已经掌握的知识,设想下如下代码的运算结果:
'a' and 'b'
'' and 'b'
'a' and 'b' and 'c'
根据python的定义,在没有看这部分内容之前,我认为答案分别为True,False,True。其实运行之后才发现应该是这样的:
Python 2.7.13+ (default, Jul 19 2017, 18:15:03)
[GCC 6.4.0 20170704] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 'a' and 'b'
'b'
>>> '' and 'b'
''
>>> 'a' and 'b' and 'c'
'c'
>>>
原因如下:
or
类似的。or的规则如下:
- 从左到右演算
- 如果有一个值为真,立即返回该值
- 所有所有的值都为假,返回最后一个假值
本文作者: Yarving Liu
本文链接:
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!