前言:代码中经常会有变量是否为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=Falseif 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 NoneFalse>>> y is NoneTrue>>> not xTrue>>> not yTrue>>> not x is NoneTrue>>> not y is NoneFalse>>> x is not NoneTrue>>> y is not NoneFalse
可以看出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:也是在谷歌推荐的写法。