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。
复制代码
1
2
3
4
5
6
7
8
9
10
11
12# 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的三种方法的全部内容,更多相关Python内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复