python中if not x: 和 if x is not None: 和 if not x is None的使用和区别(这里面有一个坑)

前言:代码中经常会有变量是否为None的判断,有三种主要的写法:
第一种是if x is None
第二种是 if not x:
第三种是if not x is None(这句这样理解更清晰if not (x is None)
如果你觉得这样写没啥区别,那么你可就要小心了,这里面有一个坑。

开始之前你必须要有一个这样的认识,清楚x等于None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()时对你的判断没有影响才行。

 not None == not False == not '' == not 0 == not [] == not {} == not ()

1、 if not x:
not与逻辑判断句if连用,代表not后面的表达式为False的时候,执行冒号后面的语句,如:

x=False
if not x:
	print('hello world')

这时,就会输出hello world,就是not x相当于if x is false, then True, else False。

2、 if x is not None: 和 if not x is None:
其实if x is not None:和 if not x is None:就是一回事,只是不同风格的写法,现在比较推荐的写法是if x is not None:,清晰明了,就是判断x是不是等于None的情况,只有x不是None的时候才会执行冒号后的语句。
看看下面的代码,可以更深入的理解:

>>> 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 is not None
True
>>> y is not None
False

可以看出not x和not y都为True,就是文章开头讲的那个知识点,not []和not None是等价的,无法区分彼此。

也许你是想判断x是否为None,但是却把x==[]的情况也判断进来了,此种情况下将无法区分。

理解if not x is None:比较好的方法是,看成if not (x is None):,这样理解起来就比较容易了,最后还是比较推荐使用if x is not None:也是在谷歌推荐的写法。

  • 7
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李先森&Mr.Li

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值