Python 判断变量是否是 None 的三种写法
代码中经常会有变量是否为None的判断,有三种主要的写法:
第一种是if x is None
;第二种是 if not x:
;第三种是if not x is None
(这句这样理解更清晰if not (x is None)
) 。如果你觉得这样写没啥区别,那么你可就要小心了,这里面有一个坑。先来看一下代码:
在学习过程中有什么不懂得可以加我的python学习交流扣扣qun,784758214群里有不错的学习视频教程、开发工具与电子书籍。与你分享python企业当下人才需求及怎么从零基础学习好python,和学习什么内容>>> 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 ()
因此在使用列表的时候,如果你想区分x==[]和x==None两种情况的话, 此时if not x:
将会出现问题:
>>> 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==[]
的情况也判断进来了,此种情况下将无法区分。
对于习惯于使用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, 空列表[], 空字典{}, 空元组()时对你的判断没有影响才行。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。