在Python中,None、空列表[]、空字典{}、空元组()、0等一系列代表空和无的对象会被转换成False。除此之外的其它对象都会被转化成True。
#!/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')
上面会输出:
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 有三种表达方式
第一种是`if x is None`; 第二种是 `if not x:`; 第三种是`if not x is None`(这句这样理解更清晰`if not (x is None)`)
注意:[]不等于None类型,也就是x==[]和x==None
重点看下面例子:
>>> 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