python and   or

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]不可能爲假,至少有一個元素
''
>>>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章