04 - 函式(Function)
← 03-控制流程 | 下一篇 → 05-常用模組
定義與呼叫
# 定義函式
def greet(name):
print(f"Hello, {name}!")
# 呼叫函式
greet("Andrew") # Hello, Andrew!
參數與回傳值
def add(a, b):
return a + b
result = add(3, 5) # 8
# 回傳多個值(其實是 tuple)
def min_max(lst):
return min(lst), max(lst)
lo, hi = min_max([3, 1, 4, 1, 5])
預設參數
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Andrew") # Hello, Andrew!
greet("Andrew", "Hi") # Hi, Andrew!
greet("Andrew", greeting="Hey") # 關鍵字引數
*args 與 **kwargs
# *args:接受任意數量的位置引數
def total(*args):
return sum(args)
total(1, 2, 3) # 6
total(1, 2, 3, 4) # 10
# **kwargs:接受任意數量的關鍵字引數
def show_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
show_info(name="Andrew", job="doctor", city="Taipei")
Lambda(匿名函式)
# 適合簡單、一次性使用的函式
square = lambda x: x ** 2
print(square(5)) # 25
# 常用於 sorted() 的 key 參數
people = [{"name": "Bob", "age": 30}, {"name": "Alice", "age": 25}]
sorted_people = sorted(people, key=lambda p: p["age"])
作用域(Scope)
x = 10 # 全域變數
def foo():
x = 20 # 區域變數(不影響全域)
print(x) # 20
foo()
print(x) # 10
# 要修改全域變數,用 global 關鍵字
def bar():
global x
x = 99
bar()
print(x) # 99
Docstring(函式說明)
def add(a, b):
"""
將兩個數字相加並回傳結果。
Args:
a: 第一個數字
b: 第二個數字
Returns:
a + b 的結果
"""
return a + b
# 查看說明
help(add)
← 03-控制流程 | 下一篇 → 05-常用模組