函式 function
是指在執行某特定任務時可以重複使用的程式碼,它會將特定的功能封裝起來,透過定義的名稱來呼叫,這樣就不必每次都需要重新寫相同的邏輯。
函式可接收參數並回傳值,是程式模組化或是結構化很好的方式。
在使用上我們可以使用def
關鍵字來定義函式,而函式要使用就必需得呼叫
它,這樣該程式碼區塊才會被執行。
在 Python 中定義函式是使用def
關鍵字。
切記!函式要被呼叫才會執行
def method_name():
.....
return .....
method_name()
Python 函式的參數非常靈活,可以分為以下幾種:
def person(name, age):
print(f"hello my name is {name}, I'm {age} years old.")
person("小明", 18)
def person(name, age=18):
print(f"hello my name is {name}, I'm {age} years old.")
person("小明")
仔細看可以發現,位置參數和預設參數只差在參數的部分age
有了預設值,當有了預設值時,在呼叫方法時可以不需要帶入參數,但是當預設值有參數而在呼叫時又帶了參數,那麼呼叫的參數會覆蓋掉預設值。
補充:/`和`*
差異/
:在這之前只能使用位置引數。*
:在這之後只能使用關鍵字引數。
def num(a, b, c, /, d, e):
return a, b, c, d, e
print(num(1, 2, 3, 4, 5)) # (1, 2, 3, 4, 5)
print(num(1, 2, 3, d=4, e=5)) # (1, 2, 3, 4, 5)
print(num(1, 2, c=3, d=4, e=5)) # TypeError: num() got some positional-only arguments passed as keyword arguments: 'c'
def num(a, b, c, *, d, e):
return a, b, c, d, e
print(num(1, 2, 3, d=4, e=5)) # (1, 2, 3, 4, 5)
print(num(1, 2, c=3, d=4, e=5)) # (1, 2, 3, 4, 5)
print(num(1, 2, 3, 4, 5)) # TypeError: num() takes 3 positional arguments but 5 were given
*
:表示把剩下的位置引數
收集起來,該形態會是元組 tuple
,值得注意的是*args
只收集『多出來』的位置引數,如果前面已經有具名的參數那麼需要先滿足先前條件。**
:表示把剩下的關鍵字引數
收集起來,該形態會是字典 dict
,需注意**kwargs
容易忽略拼寫錯誤的參數名,因為不認得的也會通通收進來。def show(*args, **kwargs):
print("args:", args)
print("kwargs:", kwargs)
show(1, 2, 3, name="小明", age=18)
*
之後的參數,呼叫時必需指定名稱。def info(a, *, b):
print(a, b)
info(1, b=2) # 正確
info(1, 2) # 錯誤
def hi(a, b, c, d):
print(a, b, c, d)
heros = ["apple", "banana", "orange", "tomato"]
hi(*heros)
heroes = {"a": "apple", "b": "banana", "c": "orange", "d": "tomato"}
hi(**heroes)
總歸來說 Python 函式是模組化、重複使用、邏輯封裝的核心工具,可以讓程式碼更加結構化、提升可讀性及可維護性
那麼今天就介紹到這,明天見ㄅㄅ!