DAY 7
4
Software Development

Day7- 如果你願意一層一層一層 的剝開繁瑣邏輯 (化簡冗長的if-else教學)

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

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

(注意:因為小馬的題目已經指明參數s是非空字串，可不必加上len(s)>0這個條件

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

``````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

範例7-1 十二生肖

``````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]+"年")
``````

範例7-2 撲克花色

``````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 nums and sum(nums) or -1
``````

課後練習

習題: 判斷閏年

``````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
``````

4 則留言

2
ccutmis
iT邦高手 4 級 ‧ 2019-09-11 07:49:21

3

iT邦大師 1 級 ‧ 2019-09-11 12:18:18
``````def isLeapYear(n):
year = int(n)
return (year % 400 == 0) or ((year % 100 != 0) and (year % 4 == 0))

ylist = [2000, 1999, 2001, 2004, 1900]

xlist = [(x, isLeapYear(x)) for x in ylist]

import calendar as cal
xlist2 = [(x, cal.isleap(x)) for x in ylist]

>>> print(xlist)
[(2000, True), (1999, False), (2001, False), (2004, True), (1900, False)]

>>> print(xlist2)
[(2000, True), (1999, False), (2001, False), (2004, True), (1900, False)]
``````

1
sixwings
iT邦新手 3 級 ‧ 2019-09-19 09:31:44

sixwings iT邦新手 3 級 ‧ 2019-09-19 10:21:18 檢舉

0
ovenchang
iT邦新手 5 級 ‧ 2020-04-16 13:45:55
``````def isLeapYear(n):
return True if not n%4 and n%100 or not n%400 else False
``````