Python判斷變量是否是None寫法代碼實例
代碼中經(jīng)常會有變量是否為None的判斷,有三種主要的寫法:
第一種是`if x is None`; 第二種是 `if not x:`; 第三種是`if not x is None`(這句這樣理解更清晰`if not (x is None)`) 。如果你覺得這樣寫沒啥區(qū)別,那么你可就要小心了,這里面有一個坑。先來看一下代碼:
>>> x = 1>>> not xFalse>>> x = [1]>>> not xFalse>>> x = 0>>> not xTrue>>> x = [0] # You don’t want to fall in this one.>>> not xFalse
在python中 None, False, 空字符串'', 0, 空列表[], 空字典{}, 空元組()都相當于False ,即:
not None == not False == not ’’ == not 0 == not [] == not {} == not ()
因此在使用列表的時候,如果你想?yún)^(qū)分x==[]和x==None兩種情況的話, 此時`if not x:`將會出現(xiàn)問題:
>>> x = []>>> y = None>>> >>> x is NoneFalse>>> y is NoneTrue>>> >>> >>> not xTrue>>> not yTrue>>> >>> >>> not x is None>>> True>>> not y is NoneFalse>>>
也許你是想判斷x是否為None,但是卻把`x==[]`的情況也判斷進來了,此種情況下將無法區(qū)分。
對于習慣于使用if not x這種寫法的pythoner,必須清楚x等于None, False, 空字符串'', 0, 空列表[], 空字典{}, 空元組()時對你的判斷沒有影響才行。
而對于`if x is not None`和`if not x is None`寫法,很明顯前者更清晰,而后者有可能使讀者誤解為`if (not x) is None`,因此推薦前者,同時這也是谷歌推薦的風格
結論:
`if x is not None`是最好的寫法,清晰,不會出現(xiàn)錯誤,以后堅持使用這種寫法。
使用if not x這種寫法的前提是:必須清楚x等于None, False, 空字符串'', 0, 空列表[], 空字典{}, 空元組()時對你的判斷沒有影響才行。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關文章:
