代碼中常常會有變量是否爲None的判斷,有三種主要的寫法:html
第一種是`if x is None`;python
第二種是 `if not x:`;git
第三種是`if not x is None`(這句這樣理解更清晰`if not (x is None)`) 。github
若是你以爲這樣寫沒啥區別,那麼你可就要當心了,這裏面有一個坑。先來看一下代碼:函數
>>> 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
在python中 None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元組()都至關於False ,即:this
<strong>not None == not False == not '' == not 0 == not [] == not {} == not ()</strong>
所以在使用列表的時候,若是你想區分x==[]和x==None兩種狀況的話, 此時`if not x:`將會出現問題:spa
>>> x = [] >>> y = None >>> >>> x is None False >>> y is None True >>> >>> >>> not x True >>> not y True >>> >>> >>> not x is None >>> True >>> not y is None False >>>
也許你是想判斷x是否爲None,可是卻把`x==[]`的狀況也判斷進來了,此種狀況下將沒法區分。code
對於習慣於使用if not x這種寫法的pythoner,必須清楚x等於None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元組()時對你的判斷沒有影響才行。 htm
而對於`if x is not None`和`if not x is None`寫法,很明顯前者更清晰,然後者有可能使讀者誤解爲`if (not x) is None`,所以推薦前者,同時這也是谷歌推薦的風格
對象
結論:
`if x is not None`是最好的寫法,清晰,不會出現錯誤,之後堅持使用這種寫法。
使用if not x這種寫法的前提是:必須清楚x等於None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元組()時對你的判斷沒有影響才行。
================================================================
不過這並不適用於變量是函數的狀況,如下轉載自:https://github.com/wklken/stackoverflow-py-top-qa/blob/master/contents/qa-control-flow.md
問題 連接
if foo is None: pass if foo == None: pass
若是比較相同的對象實例,is老是返回True 而 == 最終取決於 "eq()"
>>> class foo(object): def __eq__(self, other): return True >>> f = foo() >>> f == None True >>> f is None False >>> list1 = [1, 2, 3] >>> list2 = [1, 2, 3] >>> list1==list2 True >>> list1 is list2 False
另外
(ob1 is ob2) 等價於 (id(ob1) == id(ob2))
################################################################################
補充,2013.10.09
轉自http://zhidao.baidu.com/question/514056244.html
在python中not是邏輯判斷詞,用於布爾型True和False,not True爲False,not False爲True,如下是幾個經常使用的not的用法: (1) not與邏輯判斷句if連用,表明not後面的表達式爲False的時候,執行冒號後面的語句。好比: a = False if not a: (這裏由於a是False,因此not a就是True) print "hello" 這裏就可以輸出結果hello (2) 判斷元素是否在列表或者字典中,if a not in b,a是元素,b是列表或字典,這句話的意思是若是a不在列表b中,那麼就執行冒號後面的語句,好比: a = 5 b = [1, 2, 3] if a not in b: print "hello" 這裏也可以輸出結果hello
not x 意思至關於 if x is false, then True, else False