pythonnone判断_python 判断变量是否是 None 的三种写法

本文讨论了Python中判断变量是否为None时的三种常见写法:if x is None、if not x和if not x is None。指出在使用if not x时可能会误判空列表等情况,建议使用if x is not None作为最佳实践,因为这种方式更清晰且不易出错。同时强调,对于习惯使用if not x的程序员,需要确保了解其在特定值(如False、空字符串等)时的影响。
摘要由CSDN通过智能技术生成

代码中经常会有变量是否为None的判断,有三种主要的写法:

第一种是if x is None;

第二种是 if not x:;

第三种是if not x is None(这句这样理解更清晰if not (x is None)) 。

如果你觉得这样写没啥区别,那么你可就要小心了,这里面有一个坑。先来看一下代码:

>>> 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 ,即:

代码如下:

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

因此在使用列表的时候,如果你想区分x[]和xNone两种情况的话, 此时if not x:将会出现问题:

>>> 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==[]的情况也判断进来了,此种情况下将无法区分。

对于习惯于使用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, 空列表[], 空字典{}, 空元组()时对你的判断没有影响才行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值