python if not


判斷是否為None的情況

if not x

if x is None

if not x is None

 

if x is not None`是最好的寫法,清晰,不會出現錯誤,以后堅持使用這種寫法。

使用if not x這種寫法的前提是:必須清楚x等於None,  False, 空字符串"", 0, 空列表[], 空字典{}, 空元組()時對你的判斷沒有影響才行

 

==============轉載至http://blog.csdn.net/sasoritattoo/article/details/12451359==========

 

代碼中經常會有變量是否為None的判斷,有三種主要的寫法:

 

 第一種是`if x is None`;

 

第二種是 `if not x:`;

 

第三種是`if not x is None`(這句這樣理解更清晰`if not (x is None)`) 。

 

如果你覺得這樣寫沒啥區別,那么你可就要小心了,這里面有一個坑。先來看一下代碼:

 

[python] view plain copy
  1. >>> x = 1  
  2. >>> not x  
  3. False  
  4. >>> x = [1]  
  5. >>> not x  
  6. False  
  7. >>> x = 0  
  8. >>> not x  
  9. True  
  10. >>> x = [0]         # You don't want to fall in this one.  
  11. >>> not x  
  12. False  

 


 

在python中 None,  False, 空字符串"", 0, 空列表[], 空字典{}, 空元組()都相當於False ,即:

 

 

 

[python] view plain copy
  1. <strong>not None == not False == not '' == not 0 == not [] == not {} == not ()</strong>  


因此在使用列表的時候,如果你想區分x==[]和x==None兩種情況的話, 此時`if not x:`將會出現問題:

[python] view plain copy
  1. >>> x = []  
  2. >>> y = None  
  3. >>>   
  4. >>> x is None  
  5. False  
  6. >>> y is None  
  7. True  
  8. >>>   
  9. >>>   
  10. >>> not x  
  11. True  
  12. >>> not y  
  13. True  
  14. >>>   
  15. >>>   
  16. >>> not x is None  
  17. >>> True  
  18. >>> not y is None  
  19. False  
  20. >>>   

也許你是想判斷x是否為None,但是卻把`x==[]`的情況也判斷進來了,此種情況下將無法區分。

對於習慣於使用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`是最好的寫法,清晰,不會出現錯誤,以后堅持使用這種寫法。

 

使用if not x這種寫法的前提是:必須清楚x等於None,  False, 空字符串"", 0, 空列表[], 空字典{}, 空元組()時對你的判斷沒有影響才行。

 


 

================================================================

 

不過這並不適用於變量是函數的情況,以下轉載自:https://github.com/wklken/stackoverflow-py-top-qa/blob/master/contents/qa-control-flow.md

 

foo is None 和 foo == None的區別

問題 鏈接


如果比較相同的對象實例,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

另外


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM