match語句
match
是 Python 3.10 及以後版本引入的新特性,用於模式匹配。它允許根據對象的模式來檢查對象,並執行相應的程式碼區塊。
範例程式碼:
command = 'hello' match command: case 'hello': print('Hello there!') case 'bye': print('Goodbye!') case _: print('Command not recognized') # 使用 match 語句來檢查文字模式 text = "world" match text: case "hello": print("text is hello") case "world": print("text is world") case _: print("text is neither 'hello' or 'world'")
比較:
- if 語句: 最基本的條件控制結構,用於基於條件測試執行不同的程式碼區塊。
- match 語句: 新特性,主要用於模式匹配,特別適合處理複雜的資料結構。