使用Python的判斷語句模擬三目運(yùn)算
下面說的和三目運(yùn)算有點(diǎn)相似,但又不一樣,實(shí)在不知道該如何擬定標(biāo)題,先就是這個(gè)標(biāo)題吧,大家都知道python中沒有三目運(yùn)算,但是and/or有點(diǎn)類似三目運(yùn)算:
and/or
單獨(dú)使用表示邏輯關(guān)系與和或,也可以組和使用,用法如下
and
and前后如果某一個(gè)值為假(False, '', [], {}, None…)則返回第一個(gè)假值 如果所有值都為真則返回最后一個(gè)真值
or
如果or任意一個(gè)值為真,則立刻返回這個(gè)值 如果所有值都為假,則or返回最后一個(gè)假值
例子
result = 'test' and True # result = True result = 'test' and 'ortest' # result = ortest result = False and 'ortest' # result = False result = '' and None # result = '' result = '' or "Hall" # result = Hall result = False or None # result = None result = 'test' or 'nottest' # result = test
使用單行if else 模擬三目運(yùn)算
result if True / False else fresult if為真時(shí)候結(jié)果為result,為假的時(shí)候結(jié)果為fresult
result = 'test' if True else 'not test' # result = 'test' result = 'test' if False else 'not test' # result = 'not test'
相關(guān)文章
Python中函數(shù)參數(shù)設(shè)置及使用的學(xué)習(xí)筆記
這篇文章主要介紹了Python中函數(shù)參數(shù)設(shè)置及使用的學(xué)習(xí)筆記,記錄了一些Python2.x與Python3.x中函數(shù)參數(shù)相關(guān)的不同點(diǎn),需要的朋友可以參考下2016-05-05對(duì)numpy中array和asarray的區(qū)別詳解
下面小編就為大家分享一篇對(duì)numpy中array和asarray的區(qū)別詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-04-04Python實(shí)現(xiàn)識(shí)別手寫數(shù)字 簡易圖片存儲(chǔ)管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了Python實(shí)現(xiàn)識(shí)別手寫數(shù)字,簡易圖片存儲(chǔ)管理系統(tǒng),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01