Python 函數(shù):學會定義函數(shù),包括參數(shù)傳遞、返回值
定義函數(shù)是編程中的基本技能之一,它允許我們將代碼組織成可重用的塊。Python 提供了簡單而強大的方式來定義函數(shù),并且支持多種參數(shù)傳遞方式和返回值處理。

定義函數(shù)
使用 def 關(guān)鍵字來定義一個函數(shù)。函數(shù)定義通常包括函數(shù)名、參數(shù)列表(可選)和函數(shù)體。以下是一個簡單的例子:
def greet():
print("Hello, world!")
調(diào)用這個函數(shù)很簡單:
greet() # 輸出: Hello, world!參數(shù)傳遞
位置參數(shù) (Positional Arguments)
這是最常用的參數(shù)類型,參數(shù)按照它們在函數(shù)定義中的順序傳遞給函數(shù)。
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # 輸出: Hello, Alice!默認參數(shù) (Default Arguments)
可以為參數(shù)指定默認值,如果調(diào)用時沒有提供對應(yīng)的參數(shù),則使用默認值。
def greet(name="world"):
print(f"Hello, {name}!")
greet() # 輸出: Hello, world!
greet("Bob") # 輸出: Hello, Bob!關(guān)鍵字參數(shù) (Keyword Arguments)
您可以在調(diào)用函數(shù)時通過參數(shù)名來指定參數(shù)值,這樣就不需要考慮參數(shù)的位置。
def greet(first_name, last_name):
print(f"Hello, {first_name} {last_name}!")
greet(last_name="Smith", first_name="John") # 輸出: Hello, John Smith!可變長度參數(shù) (*args 和 **kwargs)
有時我們不知道需要傳遞多少個參數(shù),或者想要傳遞一個字典或列表作為參數(shù)。這時可以使用 *args 和 **kwargs。
*args:收集所有額外的位置參數(shù)到一個元組中。
**kwargs:收集所有額外的關(guān)鍵字參數(shù)到一個字典中。
def greet_everyone(*names):
for name in names:
print(f"Hello, {name}!")
greet_everyone("Alice", "Bob", "Charlie")
def greet_with_details(**details):
for key, value in details.items():
print(f"{key}: {value}")
greet_with_details(name="David", age=30)返回值
函數(shù)可以通過 return 語句返回一個或多個值。如果沒有顯式地使用 return,則函數(shù)會隱式地返回 None。
def add(a, b):
return a + b
result = add(5, 3)
print(result) # 輸出: 8返回多個值
Python 函數(shù)可以返回多個值,這實際上是返回了一個元組,然后可以解包為多個變量。
def get_user_info():
return "Alice", 25, "Engineer"
name, age, occupation = get_user_info()
print(name, age, occupation) # 輸出: Alice 25 Engineer示例:結(jié)合以上所有概念
下面是一個更復雜的例子,展示了如何將上述所有概念組合在一起:
def calculate_area(shape, *dimensions, **options):
"""
根據(jù)形狀計算面積,支持矩形和圓。
:param shape: 形狀名稱 ('rectangle' 或 'circle')
:param dimensions: 對于矩形,傳入兩個維度;對于圓,傳入半徑。
:param options: 其他選項,如是否打印結(jié)果。
:return: 計算出的面積
"""
if shape == 'rectangle':
length, width = dimensions
area = length * width
elif shape == 'circle':
radius, = dimensions
area = math.pi * radius ** 2
else:
raise ValueError("Unsupported shape")
if options.get('print_result', False):
print(f"The area of the {shape} is {area:.2f}")
return area
# 使用示例
calculate_area('rectangle', 10, 5, print_result=True)
calculate_area('circle', 7, print_result=True)






























