今天突然发现python还有一个if not 的判断句,遂先记下
if not系列语句主要有三种用法:
- if x is None
- if not x
- if not x is None
代码举例:
>>> x = 0
>>> not x
True
>>> x is None
False
>>> x
0
>>> not x is None
True
>>> x = None
>>> x is None
True
>>> not x is None
False
>>> x is not None
False
在 python 中,None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()都相当于False
所以使用if not 和if x is None 要注意除None以外其他false状况的影响
而if not x is None 语义不明,更加推荐使用x is not None,这也是Google推荐的写法