iT邦幫忙

2025 iThome 鐵人賽

DAY 16
0
佛心分享-IT 人自學之術

Python 學習筆記系列 第 16

筆記Day16:函式 Function

  • 分享至 

  • xImage
  •  

函式 function是指在執行某特定任務時可以重複使用的程式碼,它會將特定的功能封裝起來,透過定義的名稱來呼叫,這樣就不必每次都需要重新寫相同的邏輯。

函式可接收參數並回傳值,是程式模組化或是結構化很好的方式。

在使用上我們可以使用def關鍵字來定義函式,而函式要使用就必需得呼叫它,這樣該程式碼區塊才會被執行。

使用函式的好處

  • 重複使用:避免寫重複的邏輯。
  • 模組化:將大型程式拆分成小功能,方便維護。
  • 可讀性:好的函式命名可讓程式碼更容易閱讀。
  • 測試方便:可單獨測試該函式功能,不影響其餘內容。

函式的基本語法

在 Python 中定義函式是使用def關鍵字。

切記!函式要被呼叫才會執行

def method_name():
    .....
    return .....
method_name()

Python 函式的參數非常靈活,可以分為以下幾種:

  1. 位置參數
def person(name, age):
    print(f"hello my name is {name}, I'm {age} years old.")
person("小明", 18)
  1. 預設參數
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
  1. 可變參數
    *:表示把剩下的位置引數收集起來,該形態會是元組 tuple,值得注意的是*args只收集『多出來』的位置引數,如果前面已經有具名的參數那麼需要先滿足先前條件。
    **:表示把剩下的關鍵字引數收集起來,該形態會是字典 dict,需注意**kwargs容易忽略拼寫錯誤的參數名,因為不認得的也會通通收進來。
def show(*args, **kwargs):
    print("args:", args)
    print("kwargs:", kwargs)
show(1, 2, 3, name="小明", age=18)
  1. 強制命名參數
    *之後的參數,呼叫時必需指定名稱。
def info(a, *, b):
    print(a, b)
info(1, b=2)  # 正確
info(1, 2)    # 錯誤
  1. 引數開箱
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 函式是模組化、重複使用、邏輯封裝的核心工具,可以讓程式碼更加結構化、提升可讀性及可維護性

那麼今天就介紹到這,明天見ㄅㄅ!


上一篇
筆記Day15:條件判斷(下)
下一篇
筆記Day17:模組 Module
系列文
Python 學習筆記20
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言