- 时间:2020-07-30 21:59 编辑: 来源: 阅读:
- 扫一扫,手机访问
摘要:python代码 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)`) 。
如果你觉得这样写没啥区别,那么你可就要小心了,这里面有一个坑。先来看一下代码:
>>> 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 ,即:
[url=https://github.com/wklken/stackoverflow-py-top-qa/blob/master/contents/qa-control-flow.md]https://github.com/wklken/stackoverflow-py-top-qa/blob/master/contents/qa-control-flow.md[/url]
[b]foo is None 和 foo == None的区别[/b]
问题 [url=http://stackoverflow.com/questions/26595/is-there-any-difference-between-foo-is-none-and-foo-none]链接[/url]
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))
################################################################################
补充,2013.10.09
转自[url=http://zhidao.baidu.com/question/514056244.html]http://zhidao.baidu.com/question/514056244.html[/url]
python中的not具体表示是什么,举个例子说一下,衷心的感谢
在python中not是逻辑判断词,用于布尔型True和False,not True为False,not False为True,以下是几个常用的not的用法:
(1) not与逻辑判断句if连用,代表not后面的表达式为False的时候,执行冒号后面的语句。比如:
a = False
if not a: (这里因为a是False,所以not a就是True)
print "hello"
这里就能够输出结果hello
(2) 判断元素是否在列表或者字典中,if a not in b,a是元素,b是列表或字典,这句话的意思是如果a不在列表b中,那么就执行冒号后面的语句,比如:
a = 5
b = [1, 2, 3]
if a not in b:
print "hello"
这里也能够输出结果hello
not x 意思相当于 if x is false, then True, else False