Python函數參數:必需參數和可選參數
1. 必需參數(位置參數)
def greet_user(name):
"""基本的必需參數示例"""
print(f"你好,{name}!")
# 調用函數時必須提供參數
greet_user("小明") # 輸出:你好,小明!
greet_user() # 錯誤:缺少必需參數 'name'
2. 默認參數(可選參數)
def greet_with_title(name, title="先生"):
"""帶有默認值的參數示例"""
print(f"你好,{name}{title}!")
# 使用默認參數
greet_with_title("張") # 輸出:你好,張先生!
greet_with_title("李", "女士") # 輸出:你好,李女士!
注意事項:
- 默認參數必須放在必需參數之後
- 默認參數的值在函數定義時就已確定
- 可變對象(如列表)不建議作為默認參數
3. 關鍵字參數
def create_profile(name, age, city="北京", hobby="閱讀"):
"""關鍵字參數示例"""
return {
"name": name,
"age": age,
"city": city,
"hobby": hobby
}
# 使用關鍵字參數
profile1 = create_profile("小華", 25)
profile2 = create_profile(age=30, name="小明", hobby="游泳")
profile3 = create_profile("小李", hobby="跑步", age=28)
4. 不定數量參數
# *args:接收任意數量的位置參數
def calculate_sum(*numbers):
"""計算所有參數的總和"""
return sum(numbers)
# **kwargs:接收任意數量的關鍵字參數
def print_info(**info):
"""打印所有提供的信息"""
for key, value in info.items():
print(f"{key}: {value}")
# 使用示例
total = calculate_sum(1, 2, 3, 4, 5) # 15
print_info(name="小明", age=25, city="上海")
練習題
-
創建一個計算折扣價格的函數,接受原價和可選的折扣率(默認0.9)
-
編寫一個函數,可以接收任意數量的學生姓名和分數,並返回平均分
常見錯誤和解決方案
- SyntaxError: non-default argument follows default argument
解決方案:確保所有必需參數都在默認參數之前
- TypeError: missing required positional argument
解決方案:確保調用函數時提供所有必需的參數