Python基础教程:布尔类型bool | 您所在的位置:网站首页 › python中bool代表什么 › Python基础教程:布尔类型bool |
python 中布尔值使用常量True 和 False来表示;注意大小写 比较运算符< > == 等返回的类型就是bool类型;布尔类型通常在 if 和 while 语句中应用 这边需要注意的是,python中,bool是int的子类(继承int),故 True==1 False==0 是会返回Ture的,有点坑,如要切实判断用 xxx is True print(True==1) # 返回True print(False==0) # 返回True print(1 is True) print(0 is False)另外,还有几个坑。。。 如,Python2中True/False不是关键字,因此我们可以对其进行任意的赋值;同理,Python 中 if(True) 的效率远比不上 if(1) True = "True is not keyword in Python2" # Python2 版本中True False不是关键字,可被赋值,Python3中会报错另,由于bool是int,可进行数字计算 print(True+True) True or False 判定以下会被判定为 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,这个需要注意,与其他的语言有比较大的不同。 print(bool()) print(bool(False)) print(bool(0),bool(0.0),bool(0j)) print(bool(""),bool(()),bool([]),bool({})) class alfalse(): def __bool__(self): # 定义了 __bool__() 方法,始终返回False return False f = alfalse() print(bool(f)) class alzero(): def __len__(self): # 定义了 __len__() 方法,始终返回0 return 0 zero = alzero() print(bool(zero)) class justaclass(): pass c = justaclass() print(bool(c)) # 一般class instance都返回为True 布尔运算符 and or not OperationResultx or yif x is false, then y, else xx and yif x is false, then x, else ynot xif x is false, then True, else False注意均为小写: and or not ; 注意布尔运算的优先级低于表达式, not a == b 相当于 not (a == b), 若a == not b就会有语法错误 print((True and False),(False and False),(True and True)) print((True or False),(False or False),(True or True)) print((not True),(not False)) print( 1>1 and 11) and (11 and 1) |
今日新闻 |
推荐新闻 |
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 |