Match Case Python: New Addition to the Language

Till now, switch-case statements were not present in python. Using if-else statements and dictionary statements were some ways of implementing the switch case structure in python. But with that, the code wasn’t manageable, and even the construction was tedious. That is when the python match case comes in handy.

With the introduction of Python 3.10, several new features were introduced, and one of them was – python match case. The Python match case is similar to the switch case statement, which is recognized as structural pattern matching in python.   

NOTE: The match case structure is available for python version 3.10 and onwards.

Switch Case Structure

The switch control block has similar functionality as that of an if-else ladder. However, writing multiple if statements are not the most effective way of doing so. Instead, by using the switch case statement, we can simply combine them into a single structure.

The switch case statement in a C/C++ program would look something like this:

switch (variable to be evaluated):
{
     case value1 : //statement 1
                   break;

     case value2 : //statement 2
                   break;

     case value_n : //statement n
                    break;

     default:  //default statement
}

Match Case Statement

To implement switch-case like characteristics and if-else functionalities, we use a match case in python. A match statement will compare a given variable’s value to different shapes, also referred to as the pattern. The main idea is to keep on comparing the variable with all the present patterns until it fits into one.

Syntax of Match Case in Python

The match case consists of three main entities :

  • The match keyword
  • One or more case clauses
  • Expression for each case

The case clause consists of a pattern to be matched to the variable, a condition to be evaluated if the pattern matches, and a set of statements to be executed if the pattern matches.

We can write multiple case statements for multiple possibilities for a given variable. Each case statement has a pattern that has to be matched.

The syntax looks something like this:

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

Example of a Match Case Python Statement

Let us further understand the Match Case statement by taking a very simple example.

quit = False
match quit:
    case True:
        print("Quitting")
        exit()
    case False:
        print("System is on") 

Here, we have a variable named quit which we have assigned a Boolean value of False by default. Thus, we have a match case that will compare the patterns with the ‘quit’ variable.

We have two cases for two possible values of quit – True and False. For the first case, if the variable is True, then it will print ‘Quittting’ and execute the exit() function to end the program. In case if it is false, it will just print a statement saying that ‘System is on.’

When the quit value if False, the match case will print ‘System is on’

match case python

If the quit variable is assigned the value ‘True’, then it will print ‘Quitting’ and end the program

example match case python

If we would have used if-else, then it would be a series of the if-else ladder. However, since this match case only has two cases, using if-else would not be too tedious. But what if instead of two cases, we had 20? Then the match case would look more readable and manageable than the if-else ladder.

Also Read | 5 Ways to Check if a String is Integer in Python

Match Case Python for Function Overloading

We can also use structural pattern matching for function overloading in python. With function overloading, we have multiple functions with the same name but with a different signature.

Depending on the case condition, we can access the same function name with different signature values. With function overloading, we can improve the readability of the code.

Here, we shall be creating a user-defined function name calc() which accepts one argument. If the argument type is an integer, then we will return the square of the number. Else if the argument type is float, then we will return the cube of a number.

def calc(n:int):
	return (n**2)

def calc(n:float):
	return (n**3)  
n = 9.5
is_int = isinstance(n, int)

match is_int:
	case True : print("Square is :",calc(n))
	case False : print("Cube is:", calc(n))

Since the number n is a floating-point number, it will print the cube of the variable.

Output:

Cube is: 857.375

If we assign an integer to variable n, then it will print the square of the variable.

n = 1
match is_int:
	case True : print("Square is :",calc(n))
	case False : print("Cube is:", calc(n))

Output is:

Square is : 1

Pattern Values

The match case in python allows a number, string, ‘None’ value, ‘True’ value, and ‘False’ value as the pattern. Thus, different types of patterns are possible, and we will be looking into some of the possible patterns.

Wildcard Pattern

We can have a wildcard pattern too. A wildcard pattern is executed when none of the other pattern values are matched.

Following shows an example of a wildcard pattern.

We will take the same example of quit. But here, instead of passing a Boolean value to the variable, we will pass an integer value to the ‘quit’ variable.

quit = 4

match quit:
    case True:
        print("Quitting")
        exit()
    case False:
        print("System is on")
    case _:
        print("Boolean Value was not passed")    

The output will be:

Boolean Value was not passed

Here the underscore has been used as a wildcard pattern. It will not bind the ‘quit’ variable’s value to anything but match the variable’s value to the statement.

Multiple pattern values using OR operator

We can also have optional values for a given case. Using the OR operator, we can execute a single expression for multiple possibilities of pattern for the given variable.

In the below code, we have a variable name ‘sample’. If the variable’s value is of Boolean type, then it will execute a common statement for both the conditions. Else, for any other value, it will print ‘Not a Boolean value’.

sample = True

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

The output is:

It is a boolean value

Checking for a collection of values

The pattern can also be a collection of values. It will match the pattern against the entire collection. Let us take a list ‘list1’ as an example. We will take the entire list collection as the pattern.

list1 = ['a', 'b', 'c', 'd']

match list1:
	case ['e','f'] : print("e,f present")
	case ['a','b','c','d'] : print("a,b,c,d present")

The output will be:

a,b,c,d present

Named constants as patterns

We can have a named constant as a pattern for match case statements. The constant should be a qualified name addressed by a dot operator. It works like a literal, but it never minds.

An example of named constant is:

class switch:
	on = 1
	off = 0

status = 0

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

The output is:

Switch is off

Also Read | 4 Ways of Exiting the Program with Python Exit Function

Inline if statement in match case format

We can also add an if statement to a pattern for a match case in python. That if the condition is also known as ‘guard’. The expression for a given pattern would be evaluated only if the guard is True. If the guard is False, it does not execute that pattern’s statement.

Let us take an example for the same. We have a variable ‘n’ will is assigned a numerical value. We have three cases here – n is negative, n is zero, and n is positive. The match case will check the guard and accordingly print the statement.

n = 0
match n:
	case n if n < 0:
		print("Number is negative")
	case n if n == 0:
		print("Number is zero")
	case n if n > 0:
		print("Number is positive")

The output is:

Number is zero

FAQ’s on match case python

Why does the python match case cause an invalid error?

Implementing a python match case may cause an invalid error if you are using older versions of python. It is because the match case is present only for versions 3.10 and onwards

Why does python not have a switch till version 3.9?

Python does not have switch-case statements before version 3.10 because there were no ways to include that in a manner blended with python’s syntax and coding pattern. There had been several proposals, but none were accepted.

Which is better – match case or if-else statement?

The reason why a match case should be preferred over if-else is that it is computationally faster when compared to an if-else ladder. Also, with a match case, the code becomes more readable and manageable. These advantages are more pre-dominant when the number of conditions is significantly large.


Python match case is a new feature, and it will take some time for everyone to get adapted to it. But once you become used to it, it will definitely come in handy.

That was all for Python Match Case. If you have any questions, leave them below in the comments. Stay Tuned for more such python content.

Until then, Keep Learning!

5 1 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments