value = 42
match value:
case 1:
print("一")
case 42:
print("四十二")
case "42":
print("字串 42") # 不會進到這裡,型別不對
你可以這樣寫:
def describe(value):
match value:
case str():
print("這是字串")
case int():
print("這是整數")
case float():
print("這是浮點數")
case _:
print("其他型別")
改寫為 match...case 版本:
# 2025/03/26-00:08
def calc_discount(sale):
match sale:
case s if s >= 38000:
print(f' 銷售金額 7折優惠 {s * 0.7:,.0f}')
case s if s >= 28000:
print(f' 銷售金額 8折優惠 {s * 0.8:,.0f}')
case s if s >= 18000:
print(f' 銷售金額 9折優惠 {s * 0.9:,.0f}')
case s if s >= 8000:
print(f' 銷售金額 9.5折優惠 {s * 0.95:,.0f}')
case _:
print('未達優惠門檻')
# 範例:
calc_discount(30000) # 銷售金額 8折優惠 24,000
• case s if s >= ...: 是模式比對 + 條件守衛
• s 是從 match sale 這個值綁定過來的
• 最後的 case _: 是預設情況
# 2025/03/26-00:05
def compare(x, y):
match (x, y):
case (a, b) if a > b:
return "x 大於 y"
case (a, b) if a < b:
return "x 小於 y"
case (a, b) if a == b:
return "x 等於 y"
print(compare(5, 3)) # 輸出:x 大於 y