P11 布尔类型
(一)bool()函数
只有空字符串或等值于零的结果才是False
>>> bool(" ") True >>> bool("") False >>> bool("False") True >>> bool(False) False >>> bool(520) True >>> bool(0) False >>> bool(0.0) False >>> bool(0j) False
【笔记】结果为False的所有情况:
1.定义为False的对象:None , False
2.值为0的数字类型:0 , 0.0 , 0j , Decimal(0) , Fraction(0,1)
3.空的序列和集合:'' , () , [] , set() , range()【应用】条件语句
>>> if 520 > 250: print("520比250大") else: print("520不比250大") 520比250大
>>> if bool(250): print("250 is True") else: print("250 is False") 250 is True
【拓展】布尔类型其实就是特殊的整数类型
>>> 1 == True True >>> 0 == False True >>> True + False 1 >>> True - False 1 >>> True * False 0 >>> True / False Traceback (most recent call last): File "<pyshell#24>", line 1, in <module> True / False ZeroDivisionError: division by zero
(二)逻辑运算符(也较布尔运算)
示例:
>>> 3 < 4 and 4 < 5 True >>> 3 < 4 and 4 > 5 False >>> 3 < 4 or 4 > 5 True >>> not True False >>> not False True >>> not 250 False >>> not 0 True
任何对象可以直接进行真值测试
【问题延伸】为什么会出现上面+下面的情况?
>>> (not 1) or (0 and 1) or (3 and 4) or (5 and 6) or (7 and 8 and 9) 4
【答案】因为 and or 运算,遵从短路逻辑
P12 短路逻辑和运算符优先级
(一)短路逻辑
短路逻辑的核心思想:从左往右,只有当第一个操作数的值无法确定逻辑运算的结果时,才对第二个操作数进行求值。
>>> 3 and 4 4 >>> 4 or 5 4 >>> 0 and 3 0 >>> 0 or 3 3
(二)运算符优先级