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

 第一种是'if x is None';

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

第二种是 'if not x:';

第三种是'if not x is None'(这句这样理解更清晰'if not (x is None)') 。通常不怎么使用这种判断

 1 x = None  #True
 2 print(not x)
 3 
 4 y = False
 5 print(not y)
 6 
 7 a = 5
 8 b = [1,2,3]
 9 if a not in b:  #如果a不在b中
10     print('66')
11 
12 #要特别注意(这里有坑)
13 val = [0]
14 print(not val)  #False

在python中 None,  False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()都相当于False ,即:

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄