萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 函數定義與使用入門:溫度轉換實例、參數、返回值、文檔字串

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)

可變參數 *args, **kwargs


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)

型別提示 (Python 3.5+)

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_)。
  • 長度:超過 50 行考慮拆分。
  • 副作用:盡量避免修改全域狀態,傾向純函數。
  • 測試:為每個函數編寫單元測試 (pytest)。
copyright © 萬盛學電腦網 all rights reserved