下面說的和三目運算有點相似,但又不一樣,實在不知道該如何擬定標題,先就是這個標題吧,大家都知道python中沒有三目運算,但是and/or有點類似三目運算:
and/or
單獨使用表示邏輯關系與和或,也可以組和使用,用法如下
and
and前后如果某一個值為假(False, '', [], {}, None…)則返回第一個假值 如果所有值都為真則返回最后一個真值
or
如果or任意一個值為真,則立刻返回這個值 如果所有值都為假,則or返回最后一個假值
例子
result = 'test' and True # result = Trueresult = 'test' and 'ortest' # result = ortestresult = False and 'ortest' # result = Falseresult = '' and None # result = ''result = '' or "Hall" # result = Hallresult = False or None # result = Noneresult = 'test' or 'nottest' # result = test
使用單行if else 模擬三目運算
result if True / False else fresult if為真時候結果為result,為假的時候結果為fresult
result = 'test' if True else 'not test' # result = 'test'result = 'test' if False else 'not test' # result = 'not test'
新聞熱點
疑難解答