Python 判断None的三种方法

Python 判断None的三种方法,第1张

        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)

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/917605.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-16
下一篇2022-05-16

发表评论

登录后才能评论

评论列表(0条)

    保存