`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)`) 。


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

[python]  view plain  copy
  1. <strong>not None == not False == not '' == not 0 == not [] == not {} == not ()</strong>  

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

[python]  view plain  copy
  1. >>> x = []  
  2. >>> y = None  
  3. >>>   
  4. >>> x is None  
  5. False  
  6. >>> y is None  
  7. True  
  8. >>>   
  9. >>>   
  10. >>> not x  
  11. True  
  12. >>> not y  
  13. True  
  14. >>>   
  15. >>>   
  16. >>> not x is None  
  17. >>> True  
  18. >>> not y is None  
  19. False  
  20. >>>   
也许你是想判断x是否为None,但是却把`x==[]`的情况也判断进来了,此种情况下将无法区分。

对于习惯于使用if not x这种写法的pythoner,必须清楚x等于None,  False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()时对你的判断没有影响才行。 

而对于`if x is not None`和`if not x is None`写法,很明显前者更清晰,而后者有可能使读者误解为`if (not x) is None`,因此推荐前者,同时这也是谷歌推荐的风格

结论:

`if x is not None`是最好的写法,清晰,不会出现错误,以后坚持使用这种写法。

使用if not x这种写法的前提是:必须清楚x等于None,  False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()时对你的判断没有影响才行. 

foo is None 和 foo == None的区别

if foo is None: pass
if foo == None: pass

如果比较相同的对象实例,is总是返回True 而 == 最终取决于 "eq()"

>>> class foo(object):
    def __eq__(self, other):
        return True

>>> f = foo()
>>> f == None
True
>>> f is None
False

>>> list1 = [1, 2, 3]
>>> list2 = [1, 2, 3]
>>> list1==list2
True
>>> list1 is list2
False

另外

(ob1 is ob2) 等价于 (id(ob1) == id(ob2))



在python中not是逻辑判断词,用于布尔型True和False,not True为False,not False为True,以下是几个常用的not的用法:
(1) not与逻辑判断句if连用,代表not后面的表达式为False的时候,执行冒号后面的语句。
(2) 判断元素是否在列表或者字典中,if a not in b,a是元素,b是列表或字典,这句话的意思是如果a不在列表b中,那么就执行冒号后面的语句,


not x     意思相当于     if x is false, then True, else False
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值