首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python 函數定義與調用基礎:參數、返回值、輸入轉換實戰示例

     編輯:更多程式設計知識

溫度轉換函數完整示例


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、**kwargsdef 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')

進階:類型提示(Python 3.5+)


def convert_temp(temp: float, scale: str) -> float:
    ...

配合 mypy 靜態檢查,提前發現類型錯誤。

總結

  • 函數是代碼復用基本單元,單一職責、命名清晰;
  • 參數設計:優先位置參數,複雜場景用關鍵字參數增強可讀性;
  • 異常處理:輸入驗證、拋出具體異常;
  • 文檔字符串 + 類型提示 = 可維護的 API。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved