您的位置:首页 > 编程语言 > Python开发

python and   or

2017-03-23 11:12 274 查看
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]不可能为假,至少有一个元素
''
>>>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 表达式 second