Python判断变量是否是None写法代码实例
作者:lincappu 时间:2021-08-24 12:21:09
代码中经常会有变量是否为None的判断,有三种主要的写法:
第一种是`if x is None`;
第二种是 `if not x:`;
第三种是`if not x is None`(这句这样理解更清晰`if not (x is None)`) 。
如果你觉得这样写没啥区别,那么你可就要小心了,这里面有一个坑。先来看一下代码:
>>> x = 1
>>> not x
False
>>> x = [1]
>>> not x
False
>>> x = 0
>>> not x
True
>>> x = [0] # You don't want to fall in this one.
>>> not x
False
在python中 None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()都相当于False ,即:
not None == not False == not '' == not 0 == not [] == not {} == not ()
因此在使用列表的时候,如果你想区分x==[]和x==None两种情况的话, 此时`if not x:`将会出现问题:
>>> 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
>>>
也许你是想判断x是否为None,但是却把`x==[]`的情况也判断进来了,此种情况下将无法区分。
对于习惯于使用if not x这种写法的pythoner,必须清楚x等于None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()时对你的判断没有影响才行。
而对于`if x is not None`和`if not x is None`写法,很明显前者更清晰,而后者有可能使读者误解为`if (not x) is None`,因此推荐前者,同时这也是谷歌推荐的风格
结论:
`if x is not None`是最好的写法,清晰,不会出现错误,以后坚持使用这种写法。
使用if not x这种写法的前提是:必须清楚x等于None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()时对你的判断没有影响才行。
来源:https://www.cnblogs.com/lincappu/p/8305763.html
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
微信公众平台网页授权获取用户基本信息中授权回调域名设置的变动
![](https://img.aspxhome.com/file/2023/3/88293_0s.jpg)
Python实现用户名和密码登录
python如何写出表白程序
利用python GDAL库读写geotiff格式的遥感影像方法
python获取linux系统信息的三种方法
使用11行Python代码盗取了室友的U盘内容
![](https://img.aspxhome.com/file/2023/7/111927_0s.png)
Python 对象中的数据类型
Python代码库之Tuple如何append添加元素问题
IE中雅黑字体给布局带来的变化
![](https://img.aspxhome.com/file/UploadPic/20086/13/2008613122420492s.gif)
Python实用日期时间处理方法汇总
python中统计相同字符的个数方法实例
python 安装virtualenv和virtualenvwrapper的方法
Django之腾讯云短信的实现
![](https://img.aspxhome.com/file/2023/0/93580_0s.png)
opencv resize图片为正方形尺寸的实现方法
![](https://img.aspxhome.com/file/2023/0/92410_0s.jpg)
python识别验证码的思路及解决方案
![](https://img.aspxhome.com/file/2023/7/64677_0s.png)
Python依赖管理及打包工具Poetry使用规范
基于Tensorflow的MNIST手写数字识别分类
![](https://img.aspxhome.com/file/2023/5/103295_0s.jpg)
python 使用Tensorflow训练BP神经网络实现鸢尾花分类
![](https://img.aspxhome.com/file/2023/6/76846_0s.png)
python math模块的基本使用教程
python numpy生成等差数列、等比数列的实例
![](https://img.aspxhome.com/file/2023/6/95576_0s.jpg)