当前位置: 移动技术网 > IT编程>脚本编程>Python > python 判断变量是否是 None 的三种写法

python 判断变量是否是 None 的三种写法

2019年11月08日  | 移动技术网IT编程  | 我要评论

修路挖出16.7米蛇精,台服痞子狼,小松原绫音

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

  • 第一种是if x is none
  • 第二种是 if not x:
  • 第三种是if not x is none(这句这样理解更清晰if not (x is none)) 。

如果你觉得这样写没啥区别,那么你可就要小心了,这里面有一个坑。先来看一下代码:

>>> x = 1
>>> not x
false
>>> x = [1]
>>> not x
false
>>> x = 0
>>> not x
true
>>> x = [0]     # you don't want to fall in this one.
>>> not x
false

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

代码如下:

not none == not false == not '' == not 0 == not [] == not {} == not () 

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

>>> 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是否为none,但是却把x==[]的情况也判断进来了,此种情况下将无法区分。

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

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

结论:

if x is not none是最好的写法,清晰,不会出现错误,以后坚持使用这种写法。
使用if not x这种写法的前提是:必须清楚x等于none, false, 空字符串"", 0, 空列表[], 空字典{}, 空元组()时对你的判断没有影响才行。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网