品易云推流 关闭
文章详情页
文章 > Python基础教程 > python判断变量的方法对比

python判断变量的方法对比

python变量

头像

小妮浅浅

2021-07-28 09:27:442618浏览 · 0收藏 · 0评论

1、if x is not None是最好的写法,清晰,不会出现错误。

2、使用if not x这种写法的前提是:必须清楚x等于None、 False、 空字符串""、 空列表[]、空字典{}、空元组()时对你的判断没有影响才行。

三种方法

第一种是if x is None

第二种是 if not x:

第三种是if not x is None

#Python
 
>>> x = []
>>> y = None
>>>
>>> x is None
False
>>> y is None
True
>>>
>>>
>>> not x
True
>>> not y
True
>>>
>>>
>>> not x is None
>>> True
>>> not y is None
False
>>>

以上就是python判断变量的方法对比,希望对大家有所帮助。更多Python学习指路:python基础教程

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图