在Python中,None、空列表[]、空字典{}、空元组()、0等一系列表明空和无的对象会被转换成False。除此以外的其它对象都会被转化成True。python
#!/usr/bin/python # -*- coding: UTF-8 -*- ######测试if not######## x=0 #x='aa' #x=[] if x is None: print("x in None!") if not x: print('not x!') if not x is None: print('not x is None!') if x is not None: print('x is not None!') y=1 if y is not None: print('y is not None!') if not y: print('not y')
上面会输出:ide
not x! not x is None! x is not None! y is not None!
看下面代码
测试
>>> x=0 >>> not x True >>> x is not None True >>> not x is None True >>> >>> >>> x=156 >>> not x False >>> x is not None True >>> not x is None True >>> >>>
if not 有三种表达方式spa
第一种是`if x is None`;
第二种是 `if not x:`;
第三种是`if not x is None`(这句这样理解更清晰`if not (x is None)`) 对象
注意:[]不等于None类型,也就是x==[]和x==Noneit
重点看下面例子:class
>>> x=[] >>> y='' >>> z=0 >>> w=None >>> x is None False >>> y is None False >>> z is None False >>> w is None True >>> not x True >>> not y True >>> not z True >>> not w True >>> not x is None True >>> not y is None True >>> not z is None True >>> not z is None True >>> not w is None False