言简意赅python系列---if not x: 和 if x is not None: 和 if not x is None: 的区别

在看代码时有几个逻辑关系一直很模糊,今天来捋一捋:

  • if not x:
  • if x is not None
  • if not x is None:

开始之前你必须要有一个这样的认识,清楚x等于None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()时对你的判断没有影响才行。
即:

 not None == not False == not '' == not 0 == not [] == not {} == not ()

1、 if not x:

not与逻辑判断句if连用,代表not后面的表达式为False的时候,执行冒号后面的语句,如:

x=False
if not x:
	print('hello world')

这时,就会输出hello world

说白了,就是not x相当于if x is false, then True, else False
这一点还是相对比较好理解的。

2、 if x is not None: 和 if not x is None:

其实if x is not None:if not x is None:就是一回事,只是不同风格的写法,现在比较推荐的写法是if x is not None:,清晰明了,就是判断x是不是等于None的情况,只有x不是None的时候才会执行冒号后的语句。
看看下面的代码,可以更深入的理解:

>>> x=[]
>>> y= None
>>> x is None
False
>>> y is None
True
>>> not x
True
>>> not y
True
>>> not x is None
True
>>> not y is None
False
>>> x is not None
True
>>> y is not None
False

可以看出not xnot y都为True,就是文章开头讲的那个知识点,not []not None是等价的,无法区分彼此。

理解if not x is None:比较好的方法是,看成if not (x is None):,这样理解起来就比较容易了,最后还是比较推荐使用if x is not None:也是在谷歌推荐的写法。

欢迎大家多多交流学习 :)

你可能感兴趣的:(Python)