为什么2 != True ?

来源:互联网 发布:南风知我意2全文阅读 编辑:程序博客网 时间:2024/04/20 07:14

真值测试

True==0     # FalseTrue==1     # TrueTrue==2     # FalseFalse==0        # TrueFalse==1        # FalseFalse==2        # False

python中的任何对象都有真值,以下对象的真值为false

- None- False- zero of any numeric type,for example 0,0.0,0j.- any empty sequence,for example,'',(),[].- any empty mapping,for example,{}- instances of user-defined classes, if the class defines a __bool__() or __len__() method, when that method returns the integer zero or bool value False. 

其它所有对象的真值都被视为 true 。一些返回布尔值的操作和内置函数,总是返回0或者False来表示真值为false,返回1或者True来表示真值为true. (例外: 布尔操作 or 和 and 总是返回其操作数)

布尔操作

True and 0      # 0 0 and True      # 0True and 1      # 11 and True      # TrueTrue and 2      # 22 and True      # TrueFalse and 0     # False0 and False     # 0False and 1     # False1 and False     # FalseFalse and 2     # False2 and False     # False
True or 0       # True0 or True       # TrueTrue or 1       # True1 or True       # 1True or 2       # True2 or True       # 2False or 0      # 00 or False      # FalseFalse or 1      # 11 or False      # 1False or 2      # 22 or False      # 2

python中的布尔操作,有如下规则:

Operations Result Notes x or y if x is false,then y,else x (1) x and y if x is false,then x,else y (2) not x if x is false,then True,else False (3)

Notes:

(1) This is a short-circuit operator, so it only evaluates the second argument if the first one is false.
(2) This is a short-circuit operator, so it only evaluates the second argument if the first one is true.
(3) not has a lower priority than non-Boolean operators, so not a == b is interpreted as not (a == b), and a == not b is a syntax error.

布尔值

isinstance(True,int)    # Trueisinstance(False,int)   # TrueTrue is 1       # FalseFalse is 0      # Falseint(True)       # 1int(False)      # 0bool(2)         # Truebool(0)         # False
布尔值包括两个常量对象,分别是True和False,来表示真值;在数值上下文中,布尔值True和False等同于1和0,例如:5+True,返回了6 ;内置函数bool()可以将任何值转换为布尔值,前提是该值可以被解释为真值。

结论:2 != True ,但是 bool(2) == True 。

bool(2) == True     #True2 != True           #True
0 0
原创粉丝点击