Python Match Case Statement

The match case statement in Python introduces a powerful way to handle conditional logic, akin to the switch-case statements found in many other programming languages.Â

By allowing you to match values against a variety of patterns and execute code based on the first pattern that is matched, the match case statement can make your code more readable and expressive.

In this article, we will explore the syntax and capabilities of this feature, and demonstrate how it can be used to streamline your Python code.

Interested in discussing a Data or AI project? Feel free to reach out via email or simply complete the contact form on my website.

Â

Example 1: Matching Integers

For our first basic example, we are going to match an integer.Â

In baseball each position on the field is mapped to a number, the goal is for a user to define a position and the match case statement prints out the result.

Let’s test position = 5

match position:
    case 1:
        print("Pitcher")
    case 2:
        print("Catcher")
    case 3:
        print("First baseman")
    case 4:
        print("Second baseman")
    case 5:
        print("Third baseman")
    case 6:
        print("Shortstop")
    case 7:
        print("Left fielder")
    case 8:
        print("Center fielder")
    case 9:
        print("Right fielder")
    case _:
        print("Unknown position")

The output will be: Third baseman

Now let’s turn this into a function. This is how you will often see match case statements used.

def position_matcher(n):
  match position:
      case 1:
          print("Pitcher")
      case 2:
          print("Catcher")
      case 3:
          print("First baseman")
      case 4:
          print("Second baseman")
      case 5:
          print("Third baseman")
      case 6:
          print("Shortstop")
      case 7:
          print("Left fielder")
      case 8:
          print("Center fielder")
      case 9:
          print("Right fielder")
      case _:
          print("Unknown position")

Example 2: Matching Strings

While the first example demonstrated the use case with integers, let’s try out an example with strings.Â

In the code below we have a match case statement for Baseball Hall of Famers. These are only a few players as the baseball hall of fame has well over 300 members.

def player_hof(player_name):
  match player_name:
      case "Babe Ruth":
          print("Babe Ruth is a Hall of Famer")
      case "Willie Mays":
          print("Willie Mays is a Hall of Famer")
      case "Hank Aaron":
          print("Hank Aaron is a Hall of Famer")
      case "Ted Williams":
          print("Ted Williams is a Hall of Famer")
      case "Barry Bonds":
          print("Barry Bonds is a Hall of Famer")
      case "Ken Griffey Jr.":
          print("Ken Griffey Jr. is a Hall of Famer")
      case "Derek Jeter":
          print("Derek Jeter is a Hall of Famer")
      case "Mike Trout":
          print("Mike Trout is not a Hall of Famer")
      case _:
          print(f"{player_name} is not a Hall of Famer")

Example 3 in between values

Let’s expand on the example of utilizing integers. In this code we take a look at the amount of hits a player has. Instead of an exact match with an integer, we look at specific value ranges.

If a player has over 4,000 hits, they are considered One of the greatest. Between 3 and 4 thousand, Hall of Fame Level.

def hits_player(lifetime_hits):
  match lifetime_hits:
      case x if x > 4000:
          print("One of the greatest")
      case x if 3000 <= x < 4000:
          print("Hall of Fame level")
      case x if 2500 <= x < 3000:
          print("Borderline Hall of Fame")
      case x if 1500 <= x < 2500:
          print("All-Star")
      case x if x < 0:
          print("Invalid input")
      case _:
          print("Professional baseball player")

Example 4: Tuple

In this example we take a look at utilizing a tuple. We can compare two different values. Hits and Homeruns for a batter.

def hits_hrs_player(lifetime_hits, lifetime_hrs):
    match lifetime_hits, lifetime_hrs:
        case x, y if (x > 4000) or (y > 650):
            print("One of the greatest")
        case x, y if (3000 <= x < 4000) or (500 <= y < 650):
            print("Hall of Fame level")
        case x, y if (2500 <= x < 3000) or (400 <= y < 500):
            print("Borderline Hall of Fame")
        case x, y if (1500 <= x < 2500) or (250 <= y < 400):
            print("All-Star")
        case x, y if (x < 0) or (y < 0):
            print("Invalid input")
        case _:
            print("Professional baseball player")

Example 5: Dictionary

In this example, we take a look at using match with a dictionary.

baseball_player = {"player": {"name": "Steve Carlton", "number": 32}}
match baseball_player:
    case {"player": {"name": name, "number": number}}:
        print(f"Player {name}, number {number}")
    case _:
        print("Unknown data")

The result in this case is: Player Steve Carlton, number 32

Example 6 : Matching Lists

For the last example, we take a look at using list as input for the describe_roster function.

def describe_roster(roster):
    match roster:
        case []:
            return "No players in the roster"
        case [player]:
            return f"One player in the roster: {player}"
        case [player1, player2]:
            return f"Two players in the roster: {player1}, {player2}"
        case [player1, player2, *others]:
            return f"First two players in the roster: {player1}, {player2}, and {len(others)} more"

Leave a Reply

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