Python中使用 if not 语句判断变量是否为None

判断变量是否为None,通常有如下三种写法:

  1. if not x
  2. if not x is None
  3. if x is not None

先看如下例子:
假设变量为:None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()

看看上述三种判断方法能否将其区分!

  1. None 和 False
  2. None 和 “”
  3. None 和 0
  4. None 和 []
  5. None 和 {}
  6. None 和 ()
x=None
y=False
z=""
h=0
i=[]
j={}
k=()

print(not x)
print(not y)
print(not z)
print(not h)
print(not i)
print(not j)
print(not k)

print(not x is None)
print(not y is None)
print(not z is None)
print(not h is None)
print(not i is None)
print(not j is None)
print(not k is None)

print(x is not None)
print(y is not None)
print(z is not None)
print(h is not None)
print(i is not None)
print(j is not None)
print(k is not None)

其中打印输出结果如下:

True
True
True
True
True
True
True

False
True
True
True
True
True
True

False
True
True
True
True
True
True

从结果可以发现,

  1. if not x 并不能识别变量None 与 False, 空字符串"", 0, 空列表[], 空字典{}, 空元组() 的区别;
  2. if not x is None/ if x is not None 可以识别变量是否为None;
  3. if x is not None 可以更加直观的显示 not 的作用域。(Google)
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值