Python中对变量是否为None的判断

三种主要的写法有:

第一种:if X is None;

第二种:if not X;

当X为None,  False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()这些时,not X为真,即无法分辨出他们之间的不同。

第三种:if not X is None;

 

 在Python中,None、空列表[]、空字典{}、空元组()、0等一系列代表空和无的对象会被转换成False。除此之外的其它对象都会被转化成True。

在命令if not 1中,1便会转换为bool类型的True。not是逻辑运算符非,not 1则恒为False。因此if语句if not 1之下的语句,永远不会执行。

========================================================================================

对比:foo is None 和 foo == None

示例:

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

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

=============================================

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

 

=====================================================================================================

感谢

参考来源:http://blog.csdn.net/sasoritattoo/article/details/12451359

http://stackoverflow.com/questions/26595/is-there-any-difference-between-foo-is-none-and-foo-none

http://stackoverflow.com/questions/2710940/python-if-x-is-not-none-or-if-not-x-is-none

posted @ 2017-04-25 17:44  满月青灰  阅读(197911)  评论(1编辑  收藏  举报