注:这是自己跟着慕课嵩天老师的课程写的笔记。笔记若有错误,希望大家批评指正。
一、布尔操作符:and、or、not
and相与(乘法),or相或(加法),not取反
优先级:not、and、or
a or not b and c = (a or ((not b) and c))
二、性质
a or ture = ture
a and false = false
分配率:
a or (b and c) = (a or b) and (a or c)
a and (b or c) = (a and b) or (a and c)
not (not a) = a
德摩根定律
not(a or b) = (not a) and (not b)
not(a and b) = (not a) or (not b)
‘’’
三、特点
1.数字为零值、空字符串、空列表都被认为是false;数字为非零值、非空字符串、非空列表认为是true;bool类型仅仅是一个特殊的整数,true = 1,false = 0
print("----特点1----")
print(True+True)
print(False+True)
print(False+False)
print(bool(0))
print(bool(1))
print(bool(32))
print(bool("hello"))
print(bool(""))
print(bool("\n"))
print(bool([1,2,3]))
print(bool([]))
2.布尔运算从左到右扫描表达式一旦直到结果,就立即返回Ture或者False
内部操作逻辑如下:
x and y:If x is false, return x; otherwise, return y
x or y:If x is true, return x; otherwise, return y
not x :If x is false, return true; otherwise, return false
print("----特点2----")
response = input("yes or no")
while response[0] == 'Y' or response[0] == 'y':
print("yes")
response = input("yes or no")
while response[0] == 'Y' or 'y':
print("dead")
注:
while response[0] == ‘Y’ or response[0] == ‘y’: 不是死循环
while response[0] == ‘Y’ or ‘y’: 是死循环
因为布尔运算时or右侧的’y’始终是真,所以无论首字母是否为’Y’,该表达式均为真