不間斷 Python 挑戰 Day 12 - 函數 (Function)

2021/12/20閱讀時間約 9 分鐘
隨著程式的功能愈來愈複雜,程式碼也愈來愈多,若程式從頭寫到尾沒有任何的段落,可讀性會愈來愈差,甚至會發現同樣的一段程式碼重覆很多遍,因為類似的功能區塊在程式中可能會一再出現。這樣的程式碼不利於多人的協作開發,即使是寫作者本身在一段時間後回來看,可能也難以一眼就掌握程式的主要架構。
函數則是用來解決如這類「段落」與「重覆」的問題,函數本身也是由一系列的程式碼所組成,主要目的有兩個:
  1. 讓程式開發者可依照程式區塊的功能,包裝成較小單位的程式碼。
  2. 讓重覆使用的程式區塊可以被獨立出來,以較為精簡的方式被呼叫取用。

函數

在此之前,我們已經使用過許多Python內建的函數,例如print()、input()、range()、append()等等,這個單元我們主要在學習開發者自定義的函數,其最基本的語法如下:
def 函數名稱():
函數內容
函數名稱如變數命名規則一般,在規則內可自由定義;函數內容則是當這個函數被呼叫時所要執行的內容。回到最一開始學習Python的時候,當我們想要Python印出一行「Hello World!」的文字時,可以直接用print()函數把想打的內容放進去,也可以將這個功能包裝成一個函數,例如:
def hello():
  print("Hello World!")
呼叫這個函數即可將print()的內容印出。
hello()
執行結果:
Hello World!
雖然看起來程式的行數變多了,但若hello()需要在多個地方被呼叫,且hello()內要處理的內容變多了,例如要印出多行文字,我們就只需要修改一次hello()函數的內容,即可讓所有呼叫到這個函數的地方改變執行結果。

傳遞一個參數(parameter)的函數

如同print()函數,函數可以根據呼叫函數時所傳遞的函數做出不同的反應,也就是這個參數不是預先可以知道,而是根據程式執行到該處時當下的狀態所決定,我們可以將這個參數傳入函數中,其語法如下:
def 函數名稱(參數):
函數內容
承上例子,我們可以讓使用者輸入名字,再根據這個名字輸出訊息:
def hello_to_someone(name):
  print(f"Hello {name}!")
hello_to_someone(input("What's your name? "))
執行結果:
What's your name? WJ
Hello WJ!

傳遞多個參數的函數

延伸上一節,函數也可以傳入多個函數,視需要而定,語法如下:
def 函數名稱(參數1, 參數2, 參數3, ...):
  函數內容
例如,我們不只要輸入人名,還要輸入這個人的身高、體重,這時就可以傳遞多個參數:
def personal_info(name, height, weight):
  print(f"Hello {name}!")
  print(f"Your height is {height}!")
  print(f"Your weight is {weight}!")
info_name = input("What's your name? ")
info_height = input("Height? ")
info_weight = input("Weight? ")
personal_info(info_name, info_height, info_weight)
執行結果:
What's your name? WJ
Height? 180
Weight? 75
Hello WJ!
Your height is 180!
Your weight is 75!
傳入多個參數的用法必須注意參數的順序問題,程式並沒有辦法幫我們找出參數順序錯誤的問題,例如上例,如果呼叫函數的地方寫成:
personal_info(info_name, info_weight, info_height)
那結果就會出現不符合期待的錯誤:
What's your name? WJ
Height? 180
Weight? 75
Hello WJ!
Your height is 75!
Your weight is 180!
除了依賴開發者仔細的檢查以避免這類型的錯誤以外,我們也可以在呼叫函數時,直接將值指定給參數,如此一來參數傳入的順序就不重要了:
personal_info(name=info_name, weight=info_weight, height=info_height)

參數預設值

我們可以給參數加上預設值,承上例子,假如我們再加上一項出生地的資料,也知道程式的使用者大多數都是出生在台灣,我們可在birthplace參數加上預設值為"Taiwan",調用這個函數時,便可以不用每次都傳入此參數。
def personal_info(name, height, weight, birthplace="Taiwan"):
  print(f"Hello {name}!")
  print(f"Your height is {height}!")
  print(f"Your weight is {weight}!")
  print(f"Your birthplace is {birthplace}")
呼叫時使用預設參數:
personal_info(name="小明", height=176, weight=60)
執行結果:
Hello 小明!
Your height is 176!
Your weight is 60!
Your birthplace is Taiwan
呼叫時不使用預設參數:
personal_info(name="小華", height=160, weight=55, birthplace="Japan")
執行結果:
Hello 小華!
Your height is 160!
Your weight is 55!
Your birthplace is Japan
需要注意的是提供預設值的參數要集中在函數傳入參數的右方,因此以下的寫法在執行時是會出錯的:
def personal_info(name, height, birthplace="Taiwan", weight):
  print(f"Hello {name}!")
  print(f"Your height is {height}!")
  print(f"Your weight is {weight}!")
  print(f"Your birthplace is {birthplace}")

函數回傳值

到目前為值,我們所定義的函數都沒有定義回傳值,若用一個變數去接收函數的回傳值,會得到回傳值為None。
在函數結束前使用return語法,可將函數執行的結果,以變數、字串、串列......等等的形式回傳給主程式使用,以下範例把傳入函數的個人資料包裝成串列回傳。
def personal_info(name, height, weight, birthplace="Taiwan"):
  print(f"Hello {name}!")
  print(f"Your height is {height}!")
  print(f"Your weight is {weight}!")
  print(f"Your birthplace is {birthplace}")
  return [name, height, weight, birthplace]
personal_info_list = personal_info(name="小明", height=176, weight=60)
print(personal_info_list)
執行結果:
Hello 小明!
Your height is 176!
Your weight is 60!
Your birthplace is Taiwan
['小明', 176, 60, 'Taiwan']

程式範例

為什麼會看到廣告
Wei-Jie Weng
Wei-Jie Weng
留言0
查看全部
發表第一個留言支持創作者!