從 Python 3.10 開始,
引入了一個新的 match-case 語句,
提供了一種更簡潔和高效的方式來進行模式匹配。
x = 3
match x:
case 1:
print("x is 1")
case 2:
print("x is 2")
case _:
print("x is neither 1 nor 2")
# 複雜條件判斷
x = 5
if x > 3 and x < 10 and x % 2 == 0:
print("x is an even number between 3 and 10")
上述的條件判斷涉及多個邏輯運算子,要使用 match-case 來表達會比較困難。
def vending_machine(choice):
match choice:
case "可樂":
if stock["可樂"] > 0:
print("請取走一罐可樂")
stock["可樂"] -= 1
else:
print("可樂已售罄")
case "雪碧":
if stock["雪碧"] > 0:
print("請取走一罐雪碧")
stock["雪碧"] -= 1
else:
print("雪碧已售罄")
case "芬達":
if stock["芬達"] > 0:
print("請取走一罐芬達")
stock["芬達"] -= 1
else:
print("芬達已售罄")
case _:
print("無此飲料,請重新選擇")
# 初始化飲料庫存
stock = {
"可樂": 5,
"雪碧": 3,
"芬達": 2
}
# 客戶選擇
choice = input("請選擇飲料(可樂/雪碧/芬達):")
vending_machine(choice)