Python 函數是代碼復用的基本單元,本文以溫度轉換為例,示範函數定義 (def)、參數傳遞、返回值、型別提示、文檔字串、主程式入口守衛。
def convert_temp(temp: float, scale: str) -> float:
"""
溫度轉換
: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'")
# 呼叫
celsius = convert_temp(98.6, 'c')
print(f"98.6°F = {celsius:.1f}°C") # 37.0°C
def main():
try:
temp = float(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}")
if __name__ == '__main__':
main()
def greet(name: str, greeting: str = "Hello") -> str:
return f"{greeting}, {name}!"
print(greet("World")) # Hello, World!
print(greet("World", "Hi")) # Hi, World!
def func(a, b=2, c=3):
return a + b + c
print(func(1)) # 6
print(func(1, c=10)) # 13 (跳過 b)
def sum_all(*numbers):
return sum(numbers)
def print_kwargs(**kwargs):
for k, v in kwargs.items():
print(f"{k} = {v}")
print(sum_all(1,2,3,4)) # 10
print_kwargs(name="Alice", age=30)
from typing import List, Optional
def process(items: List[str], prefix: Optional[str] = None) -> str:
if prefix:
items = [prefix + item for item in items]
return ', '.join(items)
def calculate_area(radius: float) -> float:
"""計算圓面積
Args:
radius: 圓半徑 (非負)
Returns:
面積值
Raises:
ValueError: radius < 0
Example:
>>> calculate_area(2)
12.56637...
"""
if radius < 0:
raise ValueError("Radius must be non-negative")
return 3.14159 * radius ** 2
get_, calculate_, convert_)。pytest)。