Python代码 变量None的使用

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

 第一种是'if x is None';

第二种是 '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 ,即:

 

posted @ 2019-04-19 21:46  吃汤圆啦i  阅读(638)  评论(0编辑  收藏  举报