Python学习(四)数据结构——bool

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

Python 布尔类型 boolpython 中布尔值使用常量True 和 False来表示;注意大小写

比较运算符< > == 等返回的类型就是bool类型;布尔类型通常在 if 和 while 语句中应用

这边需要注意的是,python中,bool是int的子类(继承int),故 True==1 False==0 是会返回Ture的,有点坑,如要切实判断用 xxx is True

1PRint(True==1) # 返回True

2 print(False==0) # 返回True

3 print(1 isTrue)

4 print(0 is False)

另外,还有几个坑。。。 如,Python2中True/False不是关键字,因此我们可以对其进行任意的赋值;同理,Python 中 if(True) 的效率远比不上 if(1)

True = "True is not keyWordin Python2" # Python2 版本中True False不是关键字,可被赋值,Python3中会报错

另,由于bool是int,可进行数字计算 print(True+True)

True or False 判定以下会被判定为 False :

NoneFalsezero 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,这个需要注意,与其他的语言有比较大的不同。

1print(bool())2print(bool(False))3print(bool(0),bool(0.0),bool(0j))4print(bool(""),bool(()),bool([]),bool({}))5classalfalse():6def__bool__(self):#定义了 __bool__() 方法,始终返回False7returnFalse8f =alfalse()9print(bool(f))10classalzero():11def__len__(self):#定义了 __len__() 方法,始终返回012return013zero =alzero()14print(bool(zero))15classjustaclass():16pass17c =justaclass()18print(bool(c))#一般class instance都返回为True

布尔运算符 and or not

OperationResultxory

ifxis false, theny, elsex

xandy

ifxis false, thenx, elsey

notx

ifxis false, thenTrue, elseFalse

注意均为小写: and or not ; 注意布尔运算的优先级低于表达式, not a == b 相当于 not (a == b), 若 a == not b 就会有语法错误

1print((TrueandFalse),(FalseandFalse),(TrueandTrue))2print((TrueorFalse),(FalseorFalse),(TrueorTrue))3print((notTrue),(notFalse))4print( 1>1and1<1 )#表达式优于bool运算 相当于 print( (1>1) and (1<1) )5print( (1>1and1)<1)#加括号了,值就不一样了6print(Trueand1)#True and 数字,不建议这么使用,返回的是数字7print(Trueand111)8print(Falseand2)#False and 数字,返回False9print(not1==1)10T =True11F =False12#print(T == not F) # 会报错13print(T == (notF))#需加括号

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航