Python Match Case with Code Example

With the release of Python Programming Language 3.10, several new features were added, one of which was the Python match case. Python’s match case works like the switch case statement. This is called “structural pattern matching” in Python.

In this article, we’ll show you everything you need to know about the match case statement in python, which lets you control how your programs run in a very specific way.

Match Case in Python

In Python, we use a match case to make something work like a switch case or an if-else statement. A match statement will compare the value of a given variable to the pattern, which is a set of shapes. The main idea is to keep comparing the variable to all the existing patterns until it fits into one.

Additional information from Python Documentation, Structural pattern matching has been added in the form of a match statement and case statements of patterns with associated actions. Patterns consist of sequences, mappings, primitive data types as well as class instances. 

Syntax of Python Match Case

match variable_name:
    case ‘pattern1’ : //statement1
    case ‘pattern2’ : //statement2
    …
    case ‘pattern n’ : //statement n

There are three main parts to the match case:

  • The match keyword
  • The case clauses
  • The expression for each case

The case clause is made up of a pattern to match the variable, a condition to check if the pattern matches, and a set of statements to run if the pattern matches.

We can write more than one case statement for a variable that has more than one possible value. There is a pattern that must be followed for each case statement.

Also read: Python Sys Argv in Simple Words with Examples

Example of a Match Case Python Statement

Let’s use a very simple example to learn more about the Match Case statement.

animal_sound = "Cat"
match animal_sound:
    case "Dog":
        print("Aw! Aw! Aw!")
    case "Cat":
        print("Meow! Meow!")
    case "Cow":
        print("Mooooooo!")

In this case, we have a variable called animal_sound with the default value ‘Cat‘. As a result, we have a match case that compares the patterns to the animal_sound variable.

If the variable value is ‘Dog,’ it will print ‘Aw! Aw! Aw!‘ in the first case. If it is ‘Cat,’ it will simply print a statement that says ‘Meow! Meow!‘ If it is ‘Cow,’ it will simply print a statement that says ‘Mooooooo!‘.

If we had used if-else, it would have looked like a ladder of if-else statements. But since there are only three cases in this match case, using if-else would not be too much work.

But what if we had 20 cases instead of three? If that happened, the match case would be easier to read and work with than the if-else ladder.

Match Case Python for Function Overloading

n Python, matching a structure pattern matching can also be used for function overloading. We can have multiple functions with the same name but different signatures thanks to function overloading.

We can use different signature values to call the same function name depending on the situation. Using function overloading, we can make code easier to read.

Python does not currently support function overloading. To demonstrate, consider the following example:

In this example, we will create a user-defined function called sample that takes one argument. If the argument type is an integer, we will return the number squared. Otherwise, if the argument type is float, we will return a number’s cube.

def sample(i: int):
    return (i ** 2)


def sample(i: float):
    return (i ** 3)


i = 3.0
is_float = isinstance(i, float)

match is_float:
    case True:
        print(f"Cube of {i} is:", sample(i))
    case False:
        print(f"Square of {i} is:", sample(i))

Since the number (i) is a floating number, it will print the cube of the variable.

Output:

Cube of 3.0 is: 27.0
i = 4
is_float = isinstance(i, float)

match is_float:
    case True:
        print(f"Cube of {i} is:", sample(i))
    case False:
        print(f"Square of {i} is:", sample(i))

Output:

Square of 4 is: 64

Here, you can verify that the intended value was 8, but 64 was returned. This indicates that function overloading is unsupported.

Pattern Values

As a pattern, Python’s match case accepts a number, string, None value, True value, and False value. Thus, other types of patterns are feasible, and we will investigate several of these patterns.

Wildcard Pattern

We can also use a wildcard pattern. When none of the other pattern values are matched, a wildcard pattern is executed.

Example:

We’ll do the same thing as we did with the animal sound. But in this example, we will give the animal_sound variable an integer value.

animal_sound = 1
match animal_sound:
    case "Dog":
        print("Aw! Aw! Aw!")
    case "Cat":
        print("Meow! Meow!")
    case "Cow":
        print("Mooooooo!")
    case _:
        print("Animal Name Required!")

Output:

Animal Name Required!

Here, the underscore is a “wildcard” pattern. It won’t do anything other than match the value of the animal_sound variable to the statement.

Multiple pattern values using OR operator

For a given scenario, we can also include optional values. Using the OR operator, it is possible to execute a single expression with several pattern options for a given variable.

In the code below, there is a variable named sample. If the variable’s value is of Boolean type, a single statement will be executed for both circumstances. For all other values, it prints “Not a Boolean value“.

sample = True
 
match sample:
    case (True|False):
        print("It is a boolean value")
    case _ :
        print("Not a boolean value")

Output:

It is a boolean value

Checking for a collection of values

The pattern may alternatively be an array of values. The pattern will be matched against the complete collection. As an example, consider the list “sample_list.” As a template, we will use the complete list collection.

sample_list = [1, 2, 3, 4]

match sample_list:
    case [5, 6]:
        print("5 & 6 is Present")
    case [1, 2, 3, 4]:
        print("1, 2, 3, & 4 is Present")

Output:

1, 2, 3, & 4 is Present

Named constants as patterns

A named constant can serve as a pattern for match case statements. The constant should be a qualified name referenced with the dot operator. It functions as a literal, but nobody cares.

Example:

class Switch:
    on = 1
    off = 0


status = 1

match status:
    case Switch.on:
        print('The Switch is on')
    case Switch.off:
        print('The Switch is off')

Output:

The Switch is on

Summary

Match case in Python is a new feature, and it will take time for everyone to adjust to it. However, once you become accustomed to it, it will be quite useful.

Lastly, if you want to learn more about Python Tutorial, please leave a comment below. We’ll be happy to hear it!

Leave a Comment