python 逻辑运算符与比较运算符的差别

文章内容摘自:http://www.cnblogs.com/vamei/archive/2012/05/29/2524376.html

逻辑运算符 and, or, not

比较运算符 ==, !=, >, >=, <, <=, in

 

#5楼 2013-02-18 10:36 陳胡図  
>>> 0 == True
False
>>> 0 == False
True
>>> not 0
True
>>> 1 == True
True
>>> 1 == False
False
>>> not 1
False
>>> -1 == True
False
>>> -1 == False
False
>>> not -1
False
------------
Python 处理 -1 很奇怪么?
 
 
#6楼[楼主2013-02-18 11:03 Vamei  
@陳胡図
查阅下面的讨论:
http://stackoverflow.com/questions/7134984/why-does-1-true-but-2-true-in-python

关键在于:
True和False被当作两个整数对象。在进行比较的时候,没有进行类型转换。比如 -1 == True,相当于 -1 == 1. 
如果在条件中,比如not -1中,由于not是boolean运算符,所以进行类型装换(not bool(-1)).

这确实是个有些违反直觉的设定。
 
 
#10楼 2014-02-17 13:37 特务小强  
@Vamei
if(2):
print '2'
执行结果是2
但是2 == True 返回是False 所以在判断里面跟在表达式里面是没有任何关系的, 所以==不可靠
 
 
#11楼 2014-02-17 13:40 特务小强  
建议你把这个给补充上去,官方文档资料归纳总结的真值测试:
Any object can be tested for truth value, for use in an if or while condition or as operand of the Boolean operations below. The following values are considered false:

None

False

zero of any numeric type, for example, 0, 0L, 0.0, 0j.

any empty sequence, for example, '', (), [].

any empty mapping, for example, {}.

instances of user-defined classes, if the class defines a __nonzero__() or __len__() method, when that method returns the integer zero or bool value False. [1]

All other values are considered true — so objects of many types are always true.
posted @ 2014-04-17 09:20  cnshen  阅读(398)  评论(0)    收藏  举报