日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

python空值判斷方式(if?xxx和if?xxx?is?None的區(qū)別及說明)_python

作者:Urmsone ? 更新時(shí)間: 2022-12-27 編程語言

if xxx 和if xxx is None的區(qū)別

一、 if xxx

None,’’,0,[],{},() ,False都被判斷為空值(not xxx等價(jià))

如下代碼輸出所示,

if __name__ == '__main__':
? ? print("---not None == (not '') == (not 0) == (not []) == (not {}) == (not ()) == (not False)---")
? ? print(not None == (not '') == (not 0) == (not []) == (not {}) == (not ()) == (not False))

輸出

---not None == (not '') == (not 0) == (not []) == (not {}) == (not ()) == (not False)---
True

if xxx

如下代碼輸出所示,

if __name__ == '__main__':
? ? print("---output a,b---")
? ? a = []
? ? b = None
? ? print("a=[]")
? ? print("b=None")
? ? print("--- if x")
? ? if a:
? ? ? ? print("a")
? ? else:
? ? ? ? print("None")
? ? if b:
? ? ? ? print("b")
? ? else:
? ? ? ? print("None")

輸出

---output a,b---
a=[]
b=None
--- if x
None
None

結(jié)論:

將空列表換成上述的其他空類型,結(jié)果一樣。

如果需要過濾None值和空對(duì)象時(shí)(如[],{},''等),可使用這種寫法

二、 if xxx is None

該寫法可將None和其他空值對(duì)象區(qū)分開來

如下代碼輸出所示:

if __name__ == '__main__':
? ? a = []
? ? b = None
? ? print("a=[]")
? ? print("b=None")
? ? print("--- is None")
? ? if a is None:
? ? ? ? print("None")
? ? else:
? ? ? ? print("a")
? ? if b is None:
? ? ? ? print("None")
? ? else:
? ? ? ? print("b")

輸出

---output a,b---
a=[]
b=None
--- is None
a
None

結(jié)論:

需要區(qū)分[],{},'',()等空值對(duì)象與None的區(qū)別時(shí)時(shí)可使用這種寫法

貼下簡單的測試代碼

if __name__ == '__main__':
? ? print("---not None == (not '') == (not 0) == (not []) == (not {}) == (not ()) == (not False)---")
? ? print(not None == (not '') == (not 0) == (not []) == (not {}) == (not ()) == (not False))

? ? print("---output a,b---")
? ? a = []
? ? b = None
? ? print("a=[]")
? ? print("b=None")
? ? print("--- if x")
? ? if a:
? ? ? ? print("a")
? ? else:
? ? ? ? print("None")
? ? if b:
? ? ? ? print("b")
? ? else:
? ? ? ? print("None")

? ? print("--- is None")
? ? if a is None:
? ? ? ? print("None")
? ? else:
? ? ? ? print("a")
? ? if b is None:
? ? ? ? print("None")
? ? else:
? ? ? ? print("b")

? ? print("--- not")
? ? if not a:
? ? ? ? print("None")
? ? else:
? ? ? ? print("a")

? ? if not b:
? ? ? ? print("None")
? ? else:
? ? ? ? print("b")

? ? print("--- is not None")
? ? if a is not None:
? ? ? ? print("a")
? ? else:
? ? ? ? print("None")

? ? if b is not None:
? ? ? ? print("B")
? ? else:
? ? ? ? print("None")

原文鏈接:https://blog.csdn.net/Urms_handsomeyu/article/details/103350227

欄目分類
最近更新