Skip to main content

Match-Case Statements

Pattern Matching in Python

· 3 min read

In the previous unit, we used if, elif, and else to make decisions. Python 3.10 introduced a cleaner alternative for certain situations: the match-case statement. It's particularly useful when you're comparing one value against several possibilities.

Match-Case Statements

Basic match-case

The match-case statement checks a value against a series of patterns. When it finds a match, it runs that block and exits.

def determine_shape(sides):
match sides:
case 3:
shape = "Triangle"
case 4:
shape = "Square"
case _:
shape = "Polygon"
return shape

The underscore _ acts as a wildcard, catching anything that didn't match the earlier cases. It's like the else in an if-elif chain.

Pattern Matching with Data

Where match-case really shines is pattern matching on structured data. You can match against dictionaries and even add conditions.

def greet(person):
match person:
case {"name": "Alice", "age": age} if age > 18:
print("Hello Alice. You are an adult.")
case {"name": "Bob", "age": age} if age <= 18:
print("Hello Bob. You are a minor.")
case _:
print("Hello Stranger")

This code inspects a dictionary and extracts values while checking conditions. With if-elif-else, you'd need separate checks for each field. Pattern matching keeps it concise.

No Fall-Through

Unlike switch statements in some languages, Python's match-case doesn't fall through to the next case. Once a case matches, its block runs and the statement exits. No break needed.

When to Use Which

For simple value checks, if-elif-else works fine. match-case is better when you're matching patterns in data structures or want cleaner syntax for multiple discrete values. Both get the job done.

Project: Draw Colored Shapes with match-case

Let's rewrite the Unit 4 project using match-case instead of if-elif-else.

import turtle

screen = turtle.Screen()
screen.bgcolor("white")

t = turtle.Turtle()

num_sides = int(input("Enter the number of sides (3 to 5): "))

match num_sides:
case 3:
t.color("red")
case 4:
t.color("blue")
case 5:
t.color("green")
case _:
print("Please enter a number between 3 and 5.")
quit()

for _ in range(num_sides):
t.forward(100)
t.right(360 / num_sides)

turtle.done()

The logic is identical to the if-elif-else version. Each case maps a number of sides to a color, and the wildcard _ handles invalid input.

In the next unit, we'll look at loops and how to repeat actions with while and for.