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

day = "Monday"

match day:
case "Monday":
print("Start of the week")
case "Friday":
print("Last working day")
case "Saturday" | "Sunday":
print("Weekend!")
case _:
print("Midweek day")

✅ Output:

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

  • | is used to match multiple values.


🔹 2. Match with Numbers

number = 2

match number:
case 1:
print("One")
case 2:
print("Two")
case 3:
print("Three")
case _:
print("Unknown number")


🔹 3. Match with Tuples

You can match tuple structures directly:

point = (0, 0)

match point:
case (0, 0):
print("Origin")
case (x, 0):
print(f"X-axis at {x}")
case (0, y):
print(f"Y-axis at {y}")
case (x, y):
print(f"Point at ({x},{y})")


🔹 4. Match with Lists

numbers = [1, 2, 3]

match numbers:
case [1, 2, 3]:
print("Exact list match")
case [1, *rest]:
print(f"Starts with 1, rest: {rest}")


🔹 5. Match with Dictionaries (Mapping Patterns)

person = {"name": "Vipul", "age": 25}

match person:
case {"name": name, "age": age}:
print(f"Name: {name}, Age: {age}")

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

score = 85

match score:
case s if s >= 90:
print("Grade A+")
case s if s >= 75:
print("Grade A")
case s if s >= 60:
print("Grade B")
case _:
print("Grade C")


🔹 7. Combining Patterns

You can combine multiple values in a single case:

day = "Saturday"

match day:
case "Saturday" | "Sunday":
print("Weekend!")
case _:
print("Weekday")


🔹 8. Practical Example: Calculator

num1 = 10
num2 = 5
operation = "+"

match operation:
case "+":
print(num1 + num2)
case "-":
print(num1 - num2)
case "*":
print(num1 * num2)
case "/":
print(num1 / num2)
case _:
print("Invalid operation")


🔹 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.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *