def convert_temp(temp, scale):
"""
溫度單位轉換。
:param temp: 數值
:param scale: 'c' 華氏→攝氏, 'f' 攝氏→華氏
:return: 轉換後數值
"""
if scale == 'c':
return (temp - 32.0) * (5.0 / 9.0)
elif scale == 'f':
return temp * 9.0 / 5.0 + 32
else:
raise ValueError("scale must be 'c' or 'f'")
# 交互式調用
try:
temp = int(input('Enter a temperature: '))
scale = input('Enter the scale to convert to (c/f): ').strip().lower()
converted = convert_temp(temp, scale)
print(f'The converted temp is: {converted:.2f}')
except ValueError as e:
print(f'Error: {e}')
| 要素 | 說明 | 示例 |
|---|---|---|
def 關鍵字 | 開始定義 | def func(arg): |
| 參數列表 | 位置參數、默認參數、*args、**kwargs | def f(a, b=1, *args, **kw): |
| 文檔字符串 | """...""",help(func) 可見 | 見上方代碼 |
| 函數體 | 業務邏輯 | ... |
return | 返回值,可省略(返回 None) | return result |
# 位置參數
convert_temp(100, 'c')
# 關鍵字參數
convert_temp(temp=100, scale='c')
convert_temp(scale='c', temp=100)
# 混合(位置在前,關鍵字在後)
convert_temp(100, scale='c')
def convert_temp(temp: float, scale: str) -> float:
...
配合 mypy 靜態檢查,提前發現類型錯誤。