判断变量是否为None,通常有如下三种写法:
- if not x
- if not x is None
- if x is not None
先看如下例子:
假设变量为:None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()
看看上述三种判断方法能否将其区分!
- None 和 False
- None 和 “”
- None 和 0
- None 和 []
- None 和 {}
- None 和 ()
x=None
y=False
z=""
h=0
i=[]
j={}
k=()
print(not x)
print(not y)
print(not z)
print(not h)
print(not i)
print(not j)
print(not k)
print(not x is None)
print(not y is None)
print(not z is None)
print(not h is None)
print(not i is None)
print(not j is None)
print(not k is None)
print(x is not None)
print(y is not None)
print(z is not None)
print(h is not None)
print(i is not None)
print(j is not None)
print(k is not None)
其中打印输出结果如下:
True
True
True
True
True
True
True
False
True
True
True
True
True
True
False
True
True
True
True
True
True
从结果可以发现,
- if not x 并不能识别变量None 与 False, 空字符串"", 0, 空列表[], 空字典{}, 空元组() 的区别;
- if not x is None/ if x is not None 可以识别变量是否为None;
- if x is not None 可以更加直观的显示 not 的作用域。(Google)