代码中经常有三中方式判断变量是否为None,主要有三种写法:
(1) if x is None:
(2)if not x:
(3)if not x is None:
在python中None,False,空字符串,空列表,空字典,空元组都相当于False,
eg:not None
not False
not''
not()
not{}
not[]
这些都会返回True
另外,在使用列表的时候,如果你想区分开x==[]和x==None两种情况,此时使用if not x:会出现问题
eg:x=[]
y=None
x is None //False
y is None//True
not x//True
not y//False
not x is None//这里应该理解成not( x is None)所以其会返回结果True
not y is None//not (y is None) 其会返回结果False
综上:if x is not None:这种写法最清晰,且不会出错,推荐这种写法。