Skip to main content

Pattern Matching (match-case)

Python 3.10 introduced a clean way to check a variable against specific options called match-case.

It is a great alternative to writing long if-elif-else chains when you are comparing a variable against exact values.


1. Using match-case

Think of checking a student's grade letter ('A', 'B', 'C', 'F') and printing a custom feedback message:

grade = "B"

match grade:
case "A":
print("Excellent performance!")
case "B" | "C":
print("Good job, keep it up!") # | means "OR" (matches B or C)
case "F":
print("Don't worry. Work hard and try again.")
case _:
print("Invalid grade!") # _ is the wildcard (matches anything else)

Key Elements:

  • case "B" | "C": The vertical bar (|) acts as an OR check. This case runs if the grade is either "B" or "C".
  • case _: The underscore (_) is a wildcard. It acts like a fallback else block. If none of the other cases match, this block runs.

2. Shortcut: Inline if-else (Ternary Operator)

Sometimes you want to assign a value to a variable based on a simple check. Instead of writing a full 4-line if-else block, you can write it in a single line:

# Syntax: <value_if_true> if <condition> else <value_if_false>
marks = 45
result = "Pass" if marks >= 35 else "Fail"

print(result) # Output: Pass

Hands-On Lab Exercises

Practice writing conditionals by running these scripts on your computer:

# Exercise 1: Traffic Light Helper
light = input("Enter traffic light color (Red/Yellow/Green): ").lower()

match light:
case "red":
print("STOP!")
case "yellow":
print("Get Ready!")
case "green":
print("GO!")
case _:
print("Invalid color! Please enter Red, Yellow, or Green.")
# Exercise 2: Student Mark Validity Checker
marks = int(input("Enter your exam marks (0-100): "))

if marks < 0 or marks > 100:
print("Invalid marks! Marks must be between 0 and 100.")
elif marks >= 35:
print("Congratulations, you passed!")
else:
print("Sorry, you did not pass. Keep studying!")

Simple Q&A

Q1: Can we write a match-case statement without a fallback case _:?

Answer: Yes. However, if none of the cases match, Python will simply do nothing and move on to the next line of code. It is always safer to add a case _: block to handle unexpected values.

Q2: What is the benefit of using match-case instead of elif chains?

Answer: match-case is much cleaner to read and write when you are comparing a single variable against a list of exact matching values.


Module Summary

  • if & if-else: Choose paths in your code based on a check. Don't forget the colon (:) and indentation (4 spaces).
  • elif chains: Check multiple conditions one by one from top to bottom.
  • match-case: A clean way to match a variable against exact values.
  • Inline if-else: A one-line shortcut to choose between two values.

What's Next?

Now that we can make decisions, let's learn how to automate repetitive tasks by running code blocks multiple times using Loops!