Python 函數(shù):學(xué)會(huì)定義函數(shù),包括參數(shù)傳遞、返回值
定義函數(shù)是編程中的基本技能之一,它允許我們將代碼組織成可重用的塊。Python 提供了簡(jiǎn)單而強(qiáng)大的方式來(lái)定義函數(shù),并且支持多種參數(shù)傳遞方式和返回值處理。
定義函數(shù)
使用 def 關(guān)鍵字來(lái)定義一個(gè)函數(shù)。函數(shù)定義通常包括函數(shù)名、參數(shù)列表(可選)和函數(shù)體。以下是一個(gè)簡(jiǎn)單的例子:
def greet():
print("Hello, world!")
調(diào)用這個(gè)函數(shù)很簡(jiǎn)單:
greet() # 輸出: Hello, world!
參數(shù)傳遞
位置參數(shù) (Positional Arguments)
這是最常用的參數(shù)類型,參數(shù)按照它們?cè)诤瘮?shù)定義中的順序傳遞給函數(shù)。
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # 輸出: Hello, Alice!
默認(rèn)參數(shù) (Default Arguments)
可以為參數(shù)指定默認(rèn)值,如果調(diào)用時(shí)沒有提供對(duì)應(yīng)的參數(shù),則使用默認(rèn)值。
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ù)名來(lái)指定參數(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!
可變長(zhǎng)度參數(shù) (*args 和 **kwargs)
有時(shí)我們不知道需要傳遞多少個(gè)參數(shù),或者想要傳遞一個(gè)字典或列表作為參數(shù)。這時(shí)可以使用 *args 和 **kwargs。
*args:收集所有額外的位置參數(shù)到一個(gè)元組中。
**kwargs:收集所有額外的關(guān)鍵字參數(shù)到一個(gè)字典中。
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 語(yǔ)句返回一個(gè)或多個(gè)值。如果沒有顯式地使用 return,則函數(shù)會(huì)隱式地返回 None。
def add(a, b):
return a + b
result = add(5, 3)
print(result) # 輸出: 8
返回多個(gè)值
Python 函數(shù)可以返回多個(gè)值,這實(shí)際上是返回了一個(gè)元組,然后可以解包為多個(gè)變量。
def get_user_info():
return "Alice", 25, "Engineer"
name, age, occupation = get_user_info()
print(name, age, occupation) # 輸出: Alice 25 Engineer
示例:結(jié)合以上所有概念
下面是一個(gè)更復(fù)雜的例子,展示了如何將上述所有概念組合在一起:
def calculate_area(shape, *dimensions, **options):
"""
根據(jù)形狀計(jì)算面積,支持矩形和圓。
:param shape: 形狀名稱 ('rectangle' 或 'circle')
:param dimensions: 對(duì)于矩形,傳入兩個(gè)維度;對(duì)于圓,傳入半徑。
:param options: 其他選項(xiàng),如是否打印結(jié)果。
:return: 計(jì)算出的面積
"""
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)