Python By Sophia

Python 結構化模式匹配 (Match-Case):Python 3.10 的新特性

Python 版的 Switch-Case

長期以來,Python 缺乏類似 C/Java 的 switch-case 語法,只能用一長串 if-elif-else。Python 3.10 終於引入了 match-case

它不僅是語法糖,更支援強大的「結構化匹配」。

command = ["quit"]
match command:
    case ["quit"]:
        print("Quitting")
    case ["load", filename]:
        print(f"Loading {filename}")
    case _:
        print("Unknown command")

這在解析複雜的資料結構 (如 API 回傳的 JSON) 或處理命令列參數時非常有用,能讓程式碼邏輯更清晰、更易讀。建議在新專案中嘗試使用這個現代化語法。