← 從零開始學 Python 第 25 課,共 78 課 · 10 XP

模式比對:match

理論與題目說明

機器翻譯,尚未經母語人士審閱。

要把一個值和很多候選比較時,一長串 elif 會很笨重。從 Python 3.10 開始有 match:

command = input()
match command:
    case "start":
        print("開始")
    case "stop" | "exit":          # | 是「或」:哪一個都行
        print("停止")
    case _:                        # _ 是「其他所有情況」
        print("未知的指令")

match 能做的遠比比較字串多:例如可以把串列拆成幾個部分。

match command.split():
    case ["go", direction]:
        print("方向:", direction)  # "go north" → 方向: north
    case _:
        print("?")

題目。 讀入一個遊戲指令並回應:

  • start → 遊戲開始
  • pause → 暫停
  • stop 或 exit → 遊戲結束
  • 其他 → 未知的指令

免費註冊,就能直接在瀏覽器裡解這道題:程式碼編輯器、執行、測試檢查和提示。