1.if x is None
        2.if not x
        3.if not x is None

        在Python 中,None、False、空字符串''、空列表[]、空元组()其实都相当于False。如果x为空列表,y为None,如果你做x is None的判断,得到的是False,如果你做not x的判断,是True,也就是空列表其实是False。所以说,用第一种和第二种方法无法区分x==[]和x==None的情况。

        那么用第三种方法就可以区分出x是空列表还是None,同样的,如果x是空列表,那么not x is None结果为True,如果x是None,那么not x is None结果为False,所以用第三种方法就可以区分出x是空列表[]还是None。

# Three method of judging variable is None or Not

# 1.if x is None
# 2.if not x
# 3.if not x is None

x = []
y = None
print("not x is:", not x)
print("not y is:", not y)
print("not x is None is:", not x is None)
print("not y is None is:", not y is None)

更多推荐

Python 判断None的三种方法