6. 邏輯運算子可用來連接其它運算式,組合成較複雜的條件式
not 運算的回傳值為布林值,但 and 與 or 運算的回傳值則不⼀定是布林值
and 運算時,如果第⼀個運算元為 False,就直接回傳第⼀個運算元,⽽不
會再處理第二個運算元
or 運算時,如果第⼀個運算元為 True,就直接回傳第⼀個運算元,⽽不
會再處理第二個運算元
數值資料只要不是整數 0 就是 True,字串不是空字串就是 True
條件運算式 5/8
6
運算子 語法 執行結果 說明
and A and B 當A為False時回傳A;否則回傳B 只有A為True時,B才會被執行
or A or B 當A為True時回傳A;否則回傳B 只有A為False時,B才會被執行
not not A 當A為True時回傳False;否則回傳True
not之優先序比非邏輯運算低
not A==B執行順序為not(A==B)
7. 溫度 (temperature) 高於 30 度⽽且不超過 38 度的條件式寫法
(temperature > 30) and (temperature <= 38)
分數 (score) 必須介於 0~100 之間,則無效分數的條件式寫法
(score < 0) or (score > 100)
測試邏輯運算式
x = 8
y = 3
print(y == 3 and x < 3) #False
print(x + y == 11 or y > 8) #True
print(not (x > 0 and y > 0 or 'A' > 'C')) #False
print(not 2) #False
print(2 and 3) #3 (回傳第2個運算元)
print(2 or 3) #2 (回傳第1個運算元)
print('a' or 'b') #a (回傳第1個運算元)
print(0 and 3) #0 (回傳第1個運算元)
print('' or 'b') #b (回傳第1個運算元)
條件運算式 6/8
7
8. in 稱為成員運算子 (Membership operator),用來判斷第⼀個運算元
是否為第二個運算元的元素,若是就回傳True;否則回傳 False。
not in 運算子用來判斷第⼀個運算元是否不屬於第二個運算元的元素
第二個運算元為字串、串列...等物件
print('P' in 'Python') #True
print('x' not in 'Python') #True
print(1 in [1, 2, 3]) #True
print(2 not in [1, 2, 3]) #False
註:[1, 2, 3]為串列資料,在後續單元介紹
條件運算式 7/8
8
9. is 稱為身分運算子 (Identity operator),用來判斷兩運算元的 id 是否相
同,若是就回傳 True;否則回傳 False。所以 x is y 敘述,就等於 id(x)
== id(y) 敘述
not is 運算子用來判斷兩運算元的 id 是否不相同
要特別注意,is 運算子是用來判斷兩運算元是否引用⾃同⼀個物件,⽽
== 運算子則是判斷兩運算元的值是否相同
x = 2.5; y = 2.5
print(id(x), id(y)) #2081398578096 2081399329328 (隨執行環境變動)
print(x is y, x == y) #False True
z = x
print(id(z)) #2081398578096
print(z is x, z == x) #True True
條件運算式 8/8
9
10. Python 的 if 選擇結構敘述如下
單向選擇: if …
雙向選擇: if … else …
多向選擇: if … elif … else
巢狀選擇
選擇結構 1/9
11. 單向選擇 if…
if (條件式):
執行區塊
if敘述要以「:」冒號為結尾
選擇區塊要向右縮排 4 個空白字元
求 num 的絕對值
if (num < 0):
num = -num
成績在 55 分以上未達 60 分者,以 60 分計分
score = int(input('score:'))
if (score >= 55) and (score < 60):
score = 60
print('加分後勉予及格')
選擇結構 2/9
True
if(條件式):
區塊
False
12. 縮排的重要性
score = int(input('score:'))
if (score >= 55) and (score < 60):
score = 60
print('加分後勉予及格') #永遠都會執行
score = int(input('score:'))
if (score >= 55) and (score < 60):
score = 60
print('加分後勉予及格') #只有score大於54且小於60時,才會執行
選擇結構 3/9
12
26. 參考程式
month = int(input('請輸入⼀個 1~12 之間的月份:'))
if (month==3 or month==4 or month==5) :
print('春天')
elif (month==6 or month==7 or month==8) :
print('夏天')
elif (month==9 or month==10 or month==11) :
print('秋天')
elif (month==12 or month==1 or month==2) :
print('冬天')
else:
print('輸入錯誤!')
實作練習II 2/2
26