YouTip LogoYouTip

Python3 Match Statement

## Python3.x Python match Statement\n\n[![Image 1: Python3 Conditional Control](#) Python3 Conditional Control](#)\n\n* * *\n\n`match` is a structured pattern matching statement introduced in Python 3.10, similar to `switch-case` in other languages, but more powerful.\n\nThe match statement can match patterns in data structures, not only constant values, but also types, sequences, dictionaries, and other complex patterns.\n\n**Word Meaning**: `match` means "matching", used for pattern matching.\n\n* * *\n\n## Basic Syntax and Parameters\n\nThe match statement is a new feature of Python 3.10+, used to replace complex multi-branch if-elif structures.\n\n### Syntax Format\n\nmatch variable: case pattern1: code block1 case pattern2: code block2 case _: default code block\n\n### Pattern Types\n\n* **Constant Pattern**: Matches specific values.\n* **Wildcard Pattern**: `case _` matches any value, equivalent to default.\n* **Type Pattern**: Matches data types.\n* **Sequence Pattern**: Matches lists, tuples, and other sequences.\n* **Dictionary Pattern**: Matches dictionaries.\n* **Pattern with Guard**: Uses `if` to add additional conditions.\n\n* * *\n\n## Examples\n\n### Example 1: Basic Usage (Similar to switch)\n\n## Example\n\n# Python Version Requirement 3.10+\n\ndef http_status(status):\n\n match status:\n\n case 200:\n\nreturn"OK"\n\n case 404:\n\nreturn"Not Found"\n\n case 500:\n\nreturn"Server Error"\n\n case _:\n\nreturn"Unknown"\n\nprint(http_status(200))# Output: OK\n\nprint(http_status(404))# Output: Not Found\n\nprint(http_status(999))# Output: Unknown\n\n**Expected Output:**\n\nOK Not FoundUnknown\n\n**Code Analysis:**\n\n1. `case _` is a wildcard that matches all unmatched cases.\n2. Similar to default in switch-case.\n\n### Example 2: Multiple Value Matching\n\n## Example\n\n# Multiple values matching the same result\n\ndef color_name(code):\n\n match code:\n\n case "r" | "R":\n\nreturn"Red"\n\n case "g" | "G":\n\nreturn"Green"\n\n case "b" | "B":\n\nreturn"Blue"\n\n case _:\n\nreturn"Unknown"\n\nprint(color_name("r"))# Output: Red\n\nprint(color_name("G"))# Output: Green\n\nprint(color_name("x"))# Output: Unknown\n\n
\n\n
\n\n

Expected Output:

\n\n
Red\n\n Green\n\n Unknown\n\n
\n\n

Use | to combine multiple values into the same case.

\n\n

Example 3: Sequence Pattern Matching

\n\n
\n\n

Example

\n\n
\n\n# Sequence pattern matching\n\ndef describe_point(point):\n\n match point:\n\n case (0,0):\n\nreturn"Origin"\n\n case (x,0):\n\nreturn f"Point on X-axis ({x}, 0)"\n\n case (0, y):\n\nreturn f"Point on Y-axis (0, {y})"\n\n case (x, y):\n\nreturn f"Point in plane ({x}, {y})"\n\n case _:\n\nreturn"Invalid coordinates"\n\nprint(describe_point((0,0)))# Output: Origin\n\nprint(describe_point((5,0)))# Output: Point on X-axis (5, 0)\n\nprint(describe_point((3,4)))# Output: Point in plane (3, 4)\n\n**Expected Output:**\n\nOrigin Point on X-axis (5, 0)Point in plane (3, 4)\n\nThe match statement can deconstruct tuples/lists and extract values from them.\n\n### Example 4: Dictionary Pattern Matching\n\n## Example\n\n# Dictionary pattern matching\n\ndef process_user(user):\n\n match user:\n\n case {"name": name,"age": age}:\n\nreturn f"User: {name}, Age: {age}"\n\n case {"name": name}:\n\nreturn f"User: {name}"\n\n case _:\n\nreturn"Invalid user"\n\nprint(process_user({"name": "Tom","age": 20}))\n\nprint(process_user({"name": "Jerry"}))\n\nprint(process_user({"role": "admin"}))\n\n**Expected Output:**\n\nUser: Tom, Age: 20User: JerryInvalid user\n\nDictionary patterns can extract values of specific keys.\n\n### Example 5: Pattern with Guard\n\n## Example\n\n# Pattern matching with guards\n\ndef classify_number(n):\n\n match n:\n\n case n if n >0:\n\nreturn f"Positive ({n})"\n\n case n if n <0:\n\nreturn f"Negative ({n})"\n\n case 0:\n\nreturn"Zero"\n\nprint(classify_number(10))# Output: Positive (10)\n\nprint(classify_number(-5))# Output: Negative (-5)\n\nprint(classify_number(0))# Output: Zero\n\n# Complex conditions\n\ndef describe_list(lst):\n\n match lst:\n\n case []:\n\nreturn"Empty list"\n\n case :\n\nreturn f"Single element: {x}"\n\n case [x, y]:\n\nreturn f"Two elements: {x}, {y}"\n\n case [x, *rest]:\n\nreturn f"First: {x}, Rest: {rest}"\n\nprint(describe_list([]))\n\nprint(describe_list())\n\nprint(describe_list([1,2,3,4]))\n\n**Expected Output:**\n\nPositive (10)Negative (-5)ZeroEmpty listSingle element: 1First: 1, Rest: [2, 3, 4]\n\nUse `case variable if condition` to add additional matching conditions.\n\n* * Python3 Conditional Control](#)
← Python3 WhilePython3 Else Statement β†’