標籤:運算式 error: ace pre back 去掉 traceback bool 程式
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 defined12 >>> bool(‘y‘)13 True14 >>> bool(‘‘)15 False16 >>> 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=ans4 else:5 sport=‘football‘6 print(sport)
(2)布爾語句簡化
1 ans=input("what sports do you want[football]:")2 if ans:3 sport=ans4 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)
python-布林運算式