1、布爾表達式
條件語句和循環語句都使用布爾表達式作為條件
布爾值為真或假,以False和True表示,前面經常使用布爾表達式比較兩個值,如:while x>=0
2、布爾操作符
(1)布爾操作符: and,or和 not
布爾運算符and和or用於組合兩個布爾表達式,並產生一個布爾結果
<expr> and <expr>
<expr> or <expr>
not運算符是一個一元運算符,用來計算一個布爾表達式的反
not <expr>
(2)Python中布爾操作符的優先級,從高分到低分依次是not、 and最低是or。
所以上面的達式等於如下這個帶括號的版本
壁球比賽計分例子
a和b代表兩個壁球選手的分數
規則1:只要一個選手達到了15分,本場比賽就結束; 如果一方打了七分而另一方一分未得時,比賽也會結束
if (a==15 or b==15)or (a==7 and b==0) or (a==0 and b==7): print('比賽結束')
規則2:需要一個團隊贏得至少兩分才算贏,即其中一個隊已經達到了15分,且分數差異至少為2時比賽結束
if (a==15 or b==15)or (a==7 and b==0) or (a==0 and b==7): print('比賽繼續')
(3)布爾代數
(4)布爾表達式作為決策
只要用戶響應一個“Y” 程序就繼續。為了讓用戶輸入一個大寫或小寫,可以使用以下的循環:
對於序列類型來說,一個空序列被解釋為假,而任何非空序列被指示為真
1 >>> bool(0) 2 False 3 >>> bool(1) 4 True 5 >>> bool(32) 6 True 7 >>> bool(y) 8 Traceback (most recent call last): 9 File "<pyshell#6>", line 1, in <module> 10 bool(y) 11 NameError: name 'y' is not defined 12 >>> bool('y') 13 True 14 >>> bool('') 15 False 16 >>> bool([]) 17 False
這里可以解釋,下面的程序,是判斷response[0]等於y,或者Y,由於Y是bool型中始終為True,所以始終符合條件,形成死循環。注意布爾條件的拆分與組合。
3、布爾表達式-簡潔表示
(1)如果用戶僅僅簡單敲下回車鍵,可以使用方括號中的值作為默認值
1 ans=input("what sports do you want[football]:") 2 if ans!="": 3 sport=ans 4 else: 5 sport='football' 6 print(sport)
(2)布爾語句簡化
1 ans=input("what sports do you want[football]:") 2 if ans: 3 sport=ans 4 else: 5 sport='football' 6 print(sport)
去掉!=‘’后,只要判斷的bool語句是True,就執行。
(3)簡化
1 ans=input("what sports do you want[football]:") 2 sport=ans or 'football' 3 print(sport)