python的三目運算符和not in運算符使用示例
三目運算符也就是三元運算符
一些語言(如Java)的三元表達式形如:
判定條件?為真時的結果:為假時的結果
result=x if x
Python的三元表達式有如下幾種書寫方法:
if __name__ == '__main__': a = '' b = 'True' c = 'False' #方法一:為真時的結果 if 判定條件 else 為假時的結果 d = b if a else c print('方法一輸出結果:' + d) #方法二:判定條件 and 為真時的結果 or 為假時的結果 d = a and b or c print('方法二輸出結果:' + d) #以上兩種方法方法等同于if ... else ... if a: d = b else: d = c print('if語句的輸出結果:' + d)
輸出結果:
說明:
判斷條件:a為空串,所以判斷條件為假
當判斷條件為真時的結果:d = b
當判斷條件為假時的結果:d = c
x = [x for x in range(1,10)] print(x) y =[] result = True if 12 not in x else False # this is the best way print(result) result = True if not 12 in x else False # this way just like as " (not 12) in x" print(result) print(x is y) print(x is not y) # this is the best way print(not x is y) # this way just like as " (not x ) is y" ,so upper is the best way result = 2 if 1 < 2 else 5 if 4 > 5 else 6 # just as 1 > 2 ? 2 : 4 > 5 ? 5 : 6 print(result)
python中的not具體使用及意思
name='' while not name: name=raw_input(u'請輸入姓名:') print name
python中的not具體表示是什么:
在python中not是邏輯判斷詞,用于布爾型True和False,not True為False,not False為True,以下是幾個常用的not的用法:
(1) not與邏輯判斷句if連用,代表not后面的表達式為False的時候,執(zhí)行冒號后面的語句。比如:
a = False if not a: (這里因為a是False,所以not a就是True) print "hello"
這里就能夠輸出結果hello
(2) 判斷元素是否在列表或者字典中,if a not in b,a是元素,b是列表或字典,這句話的意思是如果a不在列表b中,那么就執(zhí)行冒號后面的語句,比如:
a = 5 b = [1, 2, 3] if a not in b: print "hello"
這里也能夠輸出結果hello
not x 意思相當于 if x is false, then True, else False
代碼中經(jīng)常會有變量是否為None的判斷,有三種主要的寫法:
第一種是`if x is None`;
第二種是 `if not x:`;
第三種是`if not x is None`(這句這樣理解更清晰`if not (x is None)`) 。
如果你覺得這樣寫沒啥區(qū)別,那么你可就要小心了,這里面有一個坑。先來看一下代碼:
>>> x = 1 >>> not x False >>> x = [1] >>> not x False >>> x = 0 >>> not x True >>> x = [0] # You don't want to fall in this one. >>> not x False
更多內(nèi)容可以參考這篇文章://www.dbjr.com.cn/article/93165.htm
相關文章
Python multiprocessing多進程原理與應用示例
這篇文章主要介紹了Python multiprocessing多進程原理與應用,結合實例形式詳細分析了基于multiprocessing包的多進程概念、原理及相關使用操作技巧,需要的朋友可以參考下2019-02-02python實現(xiàn)DEM數(shù)據(jù)的陰影生成的方法
這篇文章主要介紹了python實現(xiàn)DEM數(shù)據(jù)的陰影生成的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-07-07Python過濾函數(shù)filter()使用自定義函數(shù)過濾序列實例
這篇文章主要介紹了Python過濾函數(shù)filter()使用自定義函數(shù)過濾序列實例,配合自定義函數(shù)可以實現(xiàn)許多強大的功能,需要的朋友可以參考下2014-08-08詳解如何在ChatGPT內(nèi)構建一個Python解釋器
這篇文章主要為大家詳細介紹了如何在ChatGPT內(nèi)構建一個Python解釋器,文中的示例代碼講解詳細,具有一定的學習價值,需要的可以參考一下2023-02-02