在对一个变量是否非空(None)进行判断的时候,常见的有两种写法,但是哪一种写法才算正统呢?
太长不看版本:
1.not x,对None,[],{},0来说,都是True
2.x is not None,只对None来说是False
x = None
if not x:
print('x is None')
else:
print('x is not None')
在x为None时,上述代码的答案是显而易见的,将会打印 'x is None'
那么当x 为一些空列表或者空字典的时候,上述代码会做出怎样的判断呢?
由上可知,not x,对所有为空或者为None的对象都定义为 True。
简单来讲,not 对 [],{},0,None一视同仁。
如果在判断语句中引入None,会对判断造成影响吗?
x = None
if x is not None:
print('x is not None')
else:
print('x is None')
由上述代码可知,x is not None当然能够正确判断x 为None。
那么对于[],{},0这些呢?
is not None,只对None感兴趣啦,对于[],{},0来说,还是认为这些对象不是None