← 返回大綱
第四章

函式定義
與參數傳遞

Functions & Arguments

Scratch → Python

自製積木 → def

Scratch
定義 打招呼
說出 "Hello!"

打招呼
Python
def greet():
    print("Hello!")

greet()   # 呼叫函式
函式

參數 (Parameters)

Scratch
定義 打招呼 name
說出 "Hello, " + name
Python
def greet(name):
    print(f"Hello, {name}!")
greet("Ian")    # Hello, Ian!
greet("Alice")  # Hello, Alice!

# 多個參數
def add(a, b):
    print(a + b)

add(3, 5)   # 8
函式

回傳值 return

def add(a, b):
    return a + b        # 回傳計算結果

result = add(3, 5)
print(result)           # 8
print(add(10, 20))      # 30

# 函式可以回傳任何型別
def is_adult(age):
    return age >= 18    # 回傳布林值

print(is_adult(20))     # True
print(is_adult(15))     # False
有無 return 的差別

沒有 return 的函式會回傳 None
print() 是輸出給人看,用 return 是把值傳回給程式使用。

函式

預設參數值

def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}!")

greet("Ian")              # Hello, Ian!
greet("Alice", "嗨")     # 嗨, Alice!
greet("Bob", greeting="你好")  # 你好, Bob!

關鍵字引數

def introduce(name, age, city):
    print(f"{name}, {age} 歲, 來自 {city}")

# 用關鍵字引數,順序可以不同
introduce(age=18, city="台北", name="Ian")
函式

*args 與 **kwargs(進階)

# *args — 接受任意數量的位置引數
def total(*numbers):
    return sum(numbers)

print(total(1, 2, 3))        # 6
print(total(1, 2, 3, 4, 5))  # 15

# **kwargs — 接受任意數量的關鍵字引數
def show_info(**info):
    for key, value in info.items():
        print(f"{key}: {value}")

show_info(name="Ian", age=18, city="台北")
函式

函式的作用域 (Scope)

x = 10   # 全域變數

def func():
    y = 20   # 區域變數(只在函式內有效)
    print(x)  # 可以讀取全域變數
    print(y)

func()
print(x)  # OK
# print(y)  # 錯誤!y 在函式外不存在
global 關鍵字

如果要在函式內修改全域變數,需要用 global x 宣告,但通常不建議這樣做。

函式

lambda(匿名函式)

簡短的一行函式,適合當作引數傳遞:

# 一般函式
def square(x):
    return x ** 2

# 等同的 lambda
square = lambda x: x ** 2
print(square(5))   # 25

# 常見用途:排序時用 key 參數
students = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
students.sort(key=lambda s: s[1])   # 依分數排序
print(students)
# [('Charlie', 78), ('Alice', 85), ('Bob', 92)]
實作練習

動手試試看

# 1. 寫一個計算 BMI 的函式
def calc_bmi(weight, height):
    bmi = weight / (height ** 2)
    return round(bmi, 1)

# 2. 寫一個判斷 BMI 等級的函式
def bmi_level(bmi):
    if bmi < 18.5:
        return "體重過輕"
    elif bmi < 24:
        return "正常"
    elif bmi < 27:
        return "過重"
    else:
        return "肥胖"

# 3. 組合使用
w = float(input("體重(kg):"))
h = float(input("身高(m):"))
bmi = calc_bmi(w, h)
print(f"BMI = {bmi},{bmi_level(bmi)}")

第四章完成!

學會了 def、參數、return、預設值與 lambda。