1. 可讀性檢查
請以Python專家的立場, 依據以下規則檢查我的程式, 並以繁體中文回覆檢查結果.
檢查規則如下:
1. 每層的內縮是否使用4格空白
2. 變數的命名是否容易讓閱讀者理解其意義
3. 程式中是否有註解段落的意義
不良範例:
amount=100
if area in ('A', 'D', 'K', 'M'):
price=800
elif area in ('B', 'C', 'L', 'N'):
price=600
else:
price=500
total=price*amount
print(f'總金額={total:,}元')
在這個程式範例中, 在段落前都沒有加註註解, 不利於程式的解讀.
良好範例:
#設定數量的初值
amount=100
#判斷不同區域的單價
if area in ('A', 'D', 'K', 'M'):
price=800
elif area in ('B', 'C', 'L', 'N'):
price=600
else:
price=500
#計算總金額
total=price*amount
#輸出總金額
print(f'總金額={total:,}元')
4. 如果if敘述中存在由3個(含)以上的or或and組成的邏輯表示式, 可考慮用in或not in指令取代
不良範例1:
if area=='A' or area=='C' or area=='D' or area=='F' or area=='H' or area=='K' or area=='M' or area=='R':
total*=0.8
不良範例2:
if not (area=='A' and area=='C' and area=='D' and area=='F' and area=='H' and area=='K' and area=='M' and area=='R'):
total*=0.8
在以上的範例中,if條件式存在多個由or及and連結的條件式, 程式不易維護, 可考慮改成:
良好範例1:
if area in ('A', 'C', 'D', 'F', 'H', 'K', 'M', 'R'):
total*=0.8
良好範例2:
if area not in ('A', 'C', 'D', 'F', 'H', 'K', 'M', 'R'):
total*=0.8
5. 如果程式中存在多個if敘述, 且每個if的條件式都使用了3個(含)以上的相同變數進行判斷, 應改用if...elif...的條件分支架構.
不良範例:
if gender=='M' and salary>=100000 and saving>=1000000:
group='M1'
if gender=='M' and salary>100000 and saving<1000000:
group='M2'
if gender=='M' and salary<100000 and saving>=1000000:
group='M3'
if gender=='M' and salary<100000 and saving<1000000:
group='M4'
if gender=='F' and salary>=80000 and saving>=800000:
group='F1'
if gender=='F' and salary>80000 and saving<800000:
group='F2'
if gender=='F' and salary<80000 and saving>=800000:
group='F3'
if gender=='F' and salary<80000 and saving<800000:
group='F4'
在這個範例中, 用來作為判斷條件的值(如M, F, 100000, 1000000, 80000, 800000)重覆出現多次,
不利於維護, 應該將程式改成:
良好範例:
if gender=='M':
if salary>=100000:
if saving>=1000000:
group='M1'
else:
group='M2'
else:
if saving>=1000000:
group='M3'
else:
group='M4'
elif gender=='F':
if salary>=80000:
if saving>=800000:
group='F1'
else:
group='F2'
else:
if saving>=800000:
group='F3'
else:
group='F4'
6. 程式中的elif條件式在不影響邏輯意義的情況下, 應該去除可省略的邊界限定. 舉例:
不良範例:
if 3000 <= total:
total*=0.8
elif 2000 <= total < 3000:
total*=0.85
elif 1000 <= total < 2000:
total*=0.9
else:
total*=0.95
在這個範例中, elif條件中的邊界限定3000和2000是可以省略的,
因為已經在前一個條件中確保了total的上限, 因此, 程式的elif條件可以簡化為:
良好範例:
if 3000 <= total :
total*=0.8
elif 2000 <= total :
total*=0.85
elif 1000 <= total :
total*=0.9
else:
total*=0.95
檢查後, 請依以下方式回應:
第1項至第3項檢查項目:
如果程式符合規定, 該項目顯示"符合規定",
否則顯示"不符合規定"並說明不符合規定的原因.
第4項至第6項檢查項目:
如果程式未使用某項目的檢查句型, 該項目顯示"未使用".
如果程式沒有違反某項目的規定, 該項目顯示"符合規定".
如果程式違反某項目的規定, 說明發生錯誤的原因, 並且提供修改後的程式.
待檢查程式如下:
Last updated
Was this helpful?