2

## 【python入門教室】(8) 如果你願意一層一層一層 的剝開繁瑣邏輯 (化簡冗長的if-else教學)

if- else 程式碼可說是工程師使用頻率很高，

(基礎知識可參考: 【Python 超入門】(6) if-else邏輯: 人生最常做的事，不是吃飯睡覺，而是______ )

``````def isEven(n):
if n%2 == 0:
return True
else:
return False
``````

n%2 == 0 的值已經是True或是False了，

``````def isEven(n):
return n%2 == 0
``````

# 技巧1 – 使用三元運算式語法

``````n = 5
T=""
if type(n)==int:
T="n是整數"
else:
T="n不是整數"
``````

``````n = 5
T= "n是整數" if type(n)==int else "n不是整數"
``````

``````變數 = 值1 if 條件式 else 值2
``````

if-else一定要成對出現。

# 技巧2 – 利用in合併多個條件式

``````word = "apple"
if word[0] == 'a' or word[0] == 'e' or word[0] == 'i' or word[0] == 'o' or word[0] == 'u':
print("單字開頭為母音")
``````

``````word = "apple"
if word[0] in 'aeiou':
print("單字開頭為母音")
``````

`in`這個關鍵字除了平時較常用的與`for`搭配的語法外(例如`for i in range(3):`)，

`A in B`即是判斷物件`A`是否在容器`B`裡，

``````>>> 1 in [1,2,3]
True
>>> "a" in "apple"
True
``````

# 技巧3 – 利用列表或字典化簡大量if-else if

## 範例: 十二生肖

``````year = int(input())
if year%12 == 1:
print("今年是鼠年")
elif year%12 == 2:
print("今年是牛年")
elif year%12 == 3:
print("今年是虎年")
# …
#省略部分程式碼
# …
elif year%12 == 11:
print("今年是狗年")
elif year%12 == 0:
print("今年是豬年")
``````

``````year = int(input())
S = ["豬","鼠","牛","虎","兔","龍","蛇","馬","羊","猴","雞","狗"]
print("今年是"+S[year%12]+"年")
``````

## 範例: 撲克花色

``````letter = input()
suit = ""
if letter == 's':
suit = "黑桃"
elif letter == 'h':
suit = "紅心"
elif letter == 'd':
suit = "方塊"
elif letter == 'c':
suit = "梅花"
``````

``````letter = input()
D = {'s':"黑桃", 'h':"紅心", 'd':"方塊", 'c':"梅花"}
suit = D[letter]
``````

# 技巧4 – 化簡多重嵌套if else

``````先施放卡片效果。

若敵方生命值小於0，回傳"贏得遊戲"，否則
若卡片效果已施放十次，回傳"結束效果"，否則
回傳"繼續施放卡片效果"
``````

``````def judge():
if myHP <= 0:
return "輸掉遊戲"
else:
if enemyHp <= 0 :
return "贏得遊戲"
else:
if cnt == 10:
return "結束效果"
else:
return "繼續施放卡片放果"
``````

``````def judge():
if myHP <= 0:
return "輸掉遊戲"

if enemyHp <= 0 :
return "贏得遊戲"

if cnt == 10:
return "結束效果"

return "繼續施放卡片放果"
``````

# 技巧5 – Python高手才知道的and與or 特性

1. 元素除了0、空(如: 空字串、空列表、…)、None、False以外都當成是True。
2. and 運算若全為真，返回最右邊的真值，否則返回第一個假值
3. or 運算若全為假，返回最右邊的假值，否則返回第一個真值
4. 若同時有and, or時，and會優先計算 (就像數學算式同時有加減乘除時，先乘除後加減的道理一樣)
實際看一些例子會比較明白:
``````>>> 1 and 2 and 3

>>> False or []

>>> '0' or 0

>>> 1 and {} and False and 3

>>> 1 or 0 and 2

>>> 0 or 1 and 2

``````

## and版本-優先返回第一個假值

1. 今天是晴天 (因為媽媽覺得雨天出門穿雨衣很麻煩)
2. 超商有營業
3. 牛排肉特價20% (媽媽省吃儉用不喜歡買貴)
邏輯可以寫成
``````if 今天是晴天 and 超商有營業 and 牛排肉特價20%:
媽媽會出門買牛排肉
``````

## or版本-優先返回第一個真值

1. 參加全民英檢中級英文考試，通過初試
2. 參加多益英文考試，得到700分以上
3. 修習語言中心開設「進修英文」課程及格
邏輯可以寫成
``````if 全民英檢中級初試通過 or 多益700分以上 or 通過校內進修英文課程:
通過英文畢業門檻
``````

## 實例應用?

``````def sumOfList(nums):
return sum(nums) if len(nums)!=0 else -1
``````

``````def sumOfList(nums):
return len(nums)!=0 and sum(nums) or -1
``````

# 課後練習

## 習題一: 今天星期幾

(0: 星期日、 1:星期一、…、6: 星期六)

``````t = int(input())
if t == 0:
print("今天星期日")
elif t == 1:
print("今天星期一")
elif t == 2:
print("今天星期二")
elif t == 3:
print("今天星期三")
elif t == 4:
print("今天星期四")
elif t == 5:
print("今天星期五")
elif t == 6:
print("今天星期六")
``````

## 習題二: 判斷閏年

``````def isLeapYear(n):
if n%4==0:
if n%100!=0:
return True
else:
if n%400 ==0:
return True
else:
return False
else:
return False
``````

### 2 則留言

1
Pondudu
iT邦新手 5 級 ‧ 2020-04-20 11:12:18

``````t = int(input())
D = {0:"今天是星期日", 1:"今天是星期一", 2: "今天是星期二", 3:"今天是星期三", 4:"今天是星期四", 5:"今天是星期五", 6:"今天是星期六"}
print(D[t])
``````

``````def isLeapYear(n):
return n%4==0 and n%100!=0 or n%400==0
``````

``````def isLegal(s):
for word in "_":
ss = s.replace(word,"")
return ss.isalnum() if s[0].isupper() or s[0].islower() or s[0] == "_" else False

print(isLegal("aPPle"))  #True
print(isLegal( "_1abC"))  #True
print(isLegal("998Fg"))  #False
print(isLegal("@2fgh\$"))  #False
print(isLegal("Bk89 ag"))  #False
``````

``````def isLegal(s):
return s.replace('_','').isalnum() and not s[0].isdigit()
``````

`s[0].isdigit()`是判斷首字是數字，

Pondudu iT邦新手 5 級 ‧ 2020-04-20 13:44:05 檢舉

1
iT邦新手 5 級 ‧ 2020-04-20 15:22:24

``````t = int(input())
S = ["Sunday","Monday","Tuesday","Wednesday ","Thursday","Friday","Saturday"]
print("Today is"+S[t%7])
``````