Python match Statement
🐍 Python match Statement — Full Guide
The match statement allows you to check a value against multiple patterns and execute code for the first matching pattern.
🔹 1. Basic Match Statement
✅ Output:
-
_acts as a default case (likeelse). -
|is used to match multiple values.
🔹 2. Match with Numbers
🔹 3. Match with Tuples
You can match tuple structures directly:
🔹 4. Match with Lists
🔹 5. Match with Dictionaries (Mapping Patterns)
-
The keys must exist in the dictionary.
-
You can also use
case {"age": age} if age >= 18:for conditional matching.
🔹 6. Using if Guards in Match
You can add conditions to patterns using if:
🔹 7. Combining Patterns
You can combine multiple values in a single case:
🔹 8. Practical Example: Calculator
🔹 9. Key Points
-
Available in Python 3.10+.
-
_acts like default / else. -
Can match values, sequences, tuples, dicts.
-
Supports
ifguards and multiple patterns. -
More powerful than a traditional switch-case.
🧠 Practice Exercises
-
Match a color name and print “Primary color” or “Secondary color”.
-
Match a number tuple
(x, y)and identify origin, x-axis, y-axis, or other points. -
Create a simple menu using
matchfor addition, subtraction, multiplication, division. -
Match a dictionary representing a student and print their name and grade.
