码迷,mamicode.com
首页 > 编程语言 > 详细

python and   or

时间:2017-03-23 15:09:29      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:python   表达式   second   

python中and和or的用法

From 《dive into python》

python 中的and从左到右计算表达式,若所有值均为真,则返回最后一个值,若存在假,返回第一个假值。

or也是从左到有计算表达式,返回第一个为真的值。

IDLE 1.2.4
>>>‘a‘and‘b‘
‘b‘
>>>‘‘and‘b‘
‘‘
>>>‘a‘or‘b‘
‘a‘
>>>‘‘or‘b‘
‘b‘
类似三目表达式的用法:bool? a : b
>>> a =‘first‘
>>> b =‘second‘
>>>1and a or b   # 等价于 bool = true时的情况
‘first‘
>>>0and a or b   # 等价于 bool = false时的情况
‘second‘
>>> a =‘‘
>>>1and a or b   # a为假时,则出现问题
‘second‘
>>>(1and[a]or[b])[0]# 安全用法,因为[a]不可能为假,至少有一个元素
‘‘
>>>


本文出自 “11876896” 博客,请务必保留此出处http://11886896.blog.51cto.com/11876896/1909523

python and   or

标签:python   表达式   second   

原文地址:http://11886896.blog.51cto.com/11876896/1909523

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!