A box labeled function with arrows going in as input and arrows going out as output, illustrating the concept of a function

Python 函數 (Functions) (10)入門:把重複變成「一次寫、到處用」——定義、呼叫、參數與回傳

專案一大,就會出現同樣的步驟重複出現:先決定輸入、做運算、回傳結果。

每次都複製貼上,不但麻煩,也很難維護。

函數(Function)就是把這段「會重複的流程」裝進一個可重用的模組:它可以接收參數處理資料,並回傳結果

從此你只要「呼叫」它,就能在程式任何地方做相同的事,還能讓程式更好讀、更好測、更好改。

A box labeled function with arrows going in as input and arrows going out as output, illustrating the concept of a function

為什麼需要函數?

想像我們正在開發一個旅行規劃應用程式,每次規劃行程時都需要執行以下步驟:

  1. 確定起點和目的地 (Establish origin and destination)
  2. 計算距離和路線 (Calculate distance/route)
  3. 向用戶返回最佳路線 (Return best route)

如果沒有函數,我們需要為每一次旅行規劃重複編寫相同的代碼,這非常低效且難以維護。

什麼是函數?

函數 (Function) 是將一組相關代碼打包成可重複使用的塊,可以在程序的不同部分重複調用,而無需重新編寫相同的代碼。

函數可以:

  • 接收輸入 (通過參數 parameters)
  • 處理數據
  • 返回結果 (通過 return 語句)

函數使代碼更具模塊化、可讀性和可維護性。

定義函數 (Defining a Function)

函數定義語法 (Function Definition Syntax)

def 函數名稱():
    # 函數任務寫在這裡
    # 縮排很重要!

關鍵組成部分

  • def 關鍵字:標誌函數開始
  • 函數名稱:使用 snake_case 格式
  • 括號 ():可以包含參數
  • 冒號 ::標誌函數頭部結束
  • 縮排代碼:函數體
def trip_welcome():
 print("歡迎使用旅行規劃應用!")
 print("讓我們幫您到達目的地。")
A hand pressing a button labeled 'Call Function' that activates a sequence of code operations

呼叫函數 (Calling a Function)

定義函數後,我們需要呼叫它來執行函數體內的代碼。

呼叫函數的語法:

函數名稱()

重要提示:

  • 函數必須先定義才能呼叫
  • 呼叫時不需要縮排
  • 可以多次呼叫同一個函數
def directions_to_timesSq():
 print("步行4分鐘到34街先驅廣場車站")
 print("乘坐北行N、Q、R或W列車1站")
 print("在時代廣場42街站下車")

# 呼叫函數
directions_to_timesSq()

參數 (Parameters) 與引數 (Arguments)

函數參數允許我們的函數接受輸入數據,使函數更加靈活。

def trip_welcome(destination):
    print("歡迎使用旅行規劃應用!")
    print("看起來您今天要去" + destination + "。")

區別:

  • 參數 (Parameter):函數定義中的變量名 (如 destination)
  • 引數 (Argument):呼叫函數時傳入的實際值
trip_welcome("時代廣場") # "時代廣場"是引數
A function returning a value, illustrated as a box processing input and producing output that gets stored in a variable

返回值 (Returns)

函數可以使用 return 關鍵字將值返回給程序,以便後續使用或修改。

def calculate_exchange_usd(us_dollars, exchange_rate):
    return us_dollars * exchange_rate

new_zealand_exchange = calculate_exchange_usd(100, 1.4)
print("100美元相當於" + str(new_zealand_exchange) + "紐西蘭元")

輸出: 100美元相當於140.0紐西蘭元

儲存在變量中的函數返回值被稱為返回函數值 (returned function value)。

這使我們可以在程序的其他部分重複使用該值。

總結

  • 當你發現「同樣的程式碼出現第二次」,就該考慮抽成函數
  • 設計函數時,先想清楚四件事:名字(在說什麼事)、輸入(需要哪些參數)、處理(要做哪些步驟)、輸出(要回傳什麼)。
  • print()顯示結果;return帶回結果供後續使用——兩者用途不同,別混用。
  • 函數讓程式模組化、可讀、可維護:需求一改,改一個地方,全專案一起受益。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

High Quality

Lorem ipsum dolor sit amet, consectetur adipiscing elitsed do eiusmod tempor.

Fast Delivery

Lorem ipsum dolor sit amet, consectetur adipiscing elitsed do eiusmod tempor.

Best Warranty

Lorem ipsum dolor sit amet, consectetur adipiscing elitsed do eiusmod tempor.