Python match Statement

🐍 Python match Statement

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:

Start of the week
  • _ acts as a default case (like else).

  • | 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

  1. Available in Python 3.10+.

  2. _ acts like default / else.

  3. Can match values, sequences, tuples, dicts.

  4. Supports if guards and multiple patterns.

  5. More powerful than a traditional switch-case.


🧠 Practice Exercises

  1. Match a color name and print “Primary color” or “Secondary color”.

  2. Match a number tuple (x, y) and identify origin, x-axis, y-axis, or other points.

  3. Create a simple menu using match for addition, subtraction, multiplication, division.

  4. Match a dictionary representing a student and print their name and grade.

You may also like...