python中if not x:和if x is not None:和if not x is None:使用介绍

代码中经常有三中方式判断变量是否为None,主要有三种写法:

(1) if x is None:

(2)if not x:

(3)if not x is None:

在python中None,False,空字符串,空列表,空字典,空元组都相当于False,

eg:not None

not False

not''

not()

not{}

not[]

这些都会返回True

另外,在使用列表的时候,如果你想区分开x==[]和x==None两种情况,此时使用if not x:会出现问题

eg:x=[]

y=None

x is None //False

y is None//True

not x//True

not y//False

not x is None//这里应该理解成not( x is None)所以其会返回结果True

not y is None//not (y is None) 其会返回结果False

综上:if x is not None:这种写法最清晰,且不会出错,推荐这种写法。

  • 4
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值