python中if not x: 和 if x is not None: 和 if not x is None的使用和区别(这里面有一个坑)

前言:代码中经常会有变量是否为None的判断,有三种主要的写法:
第一种是if x is None
第二种是 if not x:
第三种是if not x is None(这句这样理解更清晰if not (x is None)
如果你觉得这样写没啥区别,那么你可就要小心了,这里面有一个坑。

开始之前你必须要有一个这样的认识,清楚x等于None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()时对你的判断没有影响才行。

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

1、 if not x:
not与逻辑判断句if连用,代表not后面的表达式为False的时候,执行冒号后面的语句,如:

x=False
if not x:
	print('hello world')

这时,就会输出hello world,就是not x相当于if x is false, then True, else False。

2、 if x is not None: 和 if not x is None:
其实if x is not None:和 if not x is None:就是一回事,只是不同风格的写法,现在比较推荐的写法是if x is not None:,清晰明了,就是判断x是不是等于None的情况,只有x不是None的时候才会执行冒号后的语句。
看看下面的代码,可以更深入的理解:

>>> 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 is not None
True
>>> y is not None
False

可以看出not x和not y都为True,就是文章开头讲的那个知识点,not []和not None是等价的,无法区分彼此。

也许你是想判断x是否为None,但是却把x==[]的情况也判断进来了,此种情况下将无法区分。

理解if not x is None:比较好的方法是,看成if not (x is None):,这样理解起来就比较容易了,最后还是比较推荐使用if x is not None:也是在谷歌推荐的写法。

猜你喜欢

转载自blog.csdn.net/weixin_44275820/article/details/108273075