iT邦幫忙

2025 iThome 鐵人賽

DAY 16
0
Software Development

學會 Python 不可怕:我每天學一點的 30 天筆記系列 第 16

Day16 : 函式基礎 – 定義、呼叫、參數、回傳值

  • 分享至 

  • xImage
  •  

如果一段程式碼要重複使用多次,難道每次都要複製貼上嗎?
解決方法:函式 (function)

函式是什麼?

  • 把一段程式碼「包起來」,讓它可以重複使用
  • 範例:print() 其實就是 Python 內建的函式

1.定義 (define) 與呼叫 (call)
在 Python 中,用 def 關鍵字定義函式,然後用函式名稱呼叫
https://ithelp.ithome.com.tw/upload/images/20250930/20178872uquZNOd9XS.png
結果會輸出
https://ithelp.ithome.com.tw/upload/images/20250930/20178872rcdgVfO0IS.png
只要定義一次,就可以呼叫很多次:
https://ithelp.ithome.com.tw/upload/images/20250930/20178872vwHAfNMR3o.png
https://ithelp.ithome.com.tw/upload/images/20250930/20178872cSke4sKwNT.png

2. 參數 (parameters)

  • 函式可以接收外部傳進來的資料,稱為參數
  • 呼叫時傳入的實際值,叫引數 (arguments)
    https://ithelp.ithome.com.tw/upload/images/20250930/20178872VuyUJsdepz.png
    結果會輸出
    https://ithelp.ithome.com.tw/upload/images/20250930/20178872M6vwNnfNaW.png

3. 回傳值 (return)
函式不一定只是印東西,還能計算後「回傳」結果,方便後續使用
https://ithelp.ithome.com.tw/upload/images/20250930/20178872FQTx5gOD2v.png
結果會輸出8
https://ithelp.ithome.com.tw/upload/images/20250930/20178872gaX2GVtQA0.png

  • def 是定義函式的關鍵字,add 是函式名稱,(a, b) 表示這個函式需要兩個數字(參數)
  • return 會把結果丟回去,交給呼叫這個函式的人
  • add(3, 5) 表示呼叫 add 函式,把 3 放進去當 a,5 放進去當 b
  • 函式算出 3 + 5 = 8,然後 return 8
  • 最後 result = 8

4. 練習1
https://ithelp.ithome.com.tw/upload/images/20250930/20178872SqIWwDWKj8.png
結果會輸出16
https://ithelp.ithome.com.tw/upload/images/20250930/20178872IVpHvIsrS3.png

  • 先定義一個函式叫 square,參數 n 代表要計算的數字

5. 練習2
https://ithelp.ithome.com.tw/upload/images/20250930/20178872tce6362PUA.png
結果會輸出
https://ithelp.ithome.com.tw/upload/images/20250930/20178872q4pkNKZZ2O.png

  • 先定義一個函式叫 average,需要三個參數 a, b, c

6.練習3
https://ithelp.ithome.com.tw/upload/images/20250930/20178872CWDX1JN8Tl.png
結果會輸出11
https://ithelp.ithome.com.tw/upload/images/20250930/20178872dJdiPSrMdG.png

  • 先定義一個函式叫 max_of_two,需要兩個參數 x 和 y

7. 練習4:偶數判斷
https://ithelp.ithome.com.tw/upload/images/20250930/20178872M0K2qBhaK4.png
結果會輸出
https://ithelp.ithome.com.tw/upload/images/20250930/20178872g2T5nkGgka.png

  • 先定義一個函式,叫 is_even,用來判斷數字是不是偶數
  • n 是函式的參數,代表要檢查的數字
  • % 是「取餘數」的運算子,n % 2 會算出 n 除以 2 的餘數

上一篇
Day15 : 進階挑戰 – 列表、字典、集合大練功 !
下一篇
Day17 : 函式進階 – 預設參數、可變參數、作用域
系列文
學會 Python 不可怕:我每天學一點的 30 天筆記18
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言