What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Implement Switch Case in Python (match case & 3 alternatives)

  • Dec 04, 2023
  • 8 Minute Read
Implement Switch Case in Python (match case & 3 alternatives)

Most programming languages have a switch or case statement that lets you execute different blocks of code based on a variable. But does Python has a Switch statement? Now, Yes. In this article, we will discuss Switch Case in Python, a new feature called match case with an example, how to use it, and 3 others methods for implementing it with code. So, let’s get started!

What is a Switch statement?

In computer programming, a switch case statement is a kind of selection control system used to allow the value of the variable to change the control flow of program execution. The switch case statement is similar to the ‘if’ statement in any programming language.

The switch case statement is a replacement of the ‘if..else’ statement in any program when we know that the choices are going to be integer or character literals. The advantages of using the Switch Case Statement in the program are as given below:

  1. It is easier to debug.
  2. It is easier to read the program to anyone except the programmer.
  3. It is easier to understand and also easier to maintain.
  4. It is easier to verify all values that are to be checked are handled.
  5. It makes the code concise.

Need of Switch Case Statement

While programming, there are times when we need to execute a specific block of code depending on some other situation. If the given situation does not satisfy, the code block is skipped and does not get executed. If we check and apply these blocks of code manually without any format, the length and complexity of the code will increase. 

A switch statement is a useful tool for testing a variable against a number of possible values and executing different instructions based on the result. It is typically an improvement to add a switch statement to a program.

Switch Statement in C++/Java

Before moving towards learning the alternatives of switch case in python language and different ways to implement it let us first understand the switch case statement in C++ or Java language. In the switch case statement, the variable is compared to the list of values. This value is known as a case value and the compiler keeps on checking the given value with all the cases until a match occurs.

The syntax for switch case statement in C++ is as given below:

switch(expression) {
   case constant-expression  :
      statement(s);
      break; //optional
   case constant-expression  :
      statement(s);
      break; //optional
  
   // multiple number of case statement is allowed 
   default : //Optional
      statement(s);
}

 

Explanation of the Code: 

  • Expression: It should be an integral type or enumerated type.
  • Constant expression: The constant expression should have the same data type as the variable to be compared with and also it must be literal or constant.
  • Break: The break statement is used to terminate the switch statement if the case value matches the variable value. After the break statement, the flow control of the program jumps to the next line of code immediately after the switch case statement.
  • Default: The default case is used in a switch statement for the situation where no case is executed. Declaring the default case is optional.                                                                                                   

Does Python have a Switch statement?

Yes, Python does have a Switch case functionality. Since Python 3.10, we can now use a new syntax to implement this type of functionality with a match case. The match case statement allows users to implement code snippets exactly to switch cases.

It can be used to pass the variable to compare and the case statements can be used to define the commands to execute when one case matches.

How to use match case in Python?

The match-case statement consists of a series of case blocks, each of which specifies a pattern to match against the value. If a match is found, the corresponding code block is executed. If no match is found, an optional default block can be used to specify a default action.

Python added this feature with the 3.10 release in October of 2021 under "Structural Pattern Matching". It can be implemented in a very similar manner as we do in C, Java, or Javascript. The match case command is more easier and powerful.

It consists of 2 main components :

  1. The “match” keyword
  2. The case clause(s) with each condition/statement

A pattern that matches the variable, a condition that determines whether the pattern matches, and a series of statements that are to be executed if the pattern matches make up the case clause.

For numerous potential results of a given variable, we can create numerous case statements. A pattern must be matched in each case statement.

Let's look at how to implement it:

Syntax:

match subject:
    case <pattern_1>:
        <action_1>
    case <pattern_2>:
        <action_2>
    case <pattern_3>:
        <action_3>
    case _:
        <action_wildcard>

 

Example:

user_input = int(input("enter your lucky number between 1-5\n"))

match user_input:

        case 1:

         print( "you will have a new house")

        case 2:

         print( "you will receive good news ")

        case 3:

         print( "you will get a car")

        case 4:

         print( "you might face your fear this week")

        case 5:

         print( "you will get a pet")

 

Output:

enter your lucky number between 1-5
5
you will get a pet

 

Other Alternatives

We can also use 3 different replacements to implement a python switch case:

  1. If-elif-else
  2. Dictionary Mapping
  3. Using classes

Let us understand each python switch syntax one by one in detail below:

Method 01) If-elif-else

If-elif is the shortcut for the if-else if-else chain. We can use the if-elif statement and add the else statement at the end which is performed if none of the above if-elif statements is true. The if-elif chain allows you to handle multiple conditions inside one block.

Example:

# if-elif statement example 

fruit = 'Banana'

if fruit == 'Mango': 
    print("letter is Mango") 

elif fruit == "Grapes": 
    print("letter is Grapes") 

elif fruit == "Banana": 
    print("fruit is Banana") 

else: 
    print("fruit isn't Banana, Mango or Grapes") 

 

Output:

fruit is Banana

 

Method 02) Dictionary Mapping

If you know the basic python language then you must be familiar with a dictionary and its pattern of storing a group of objects in memory using key-value pairs. So, when we use the dictionary to replace the Switch case statement, the key value of the dictionary data type works as cases in a switch statement.

Example:

# Implement Python Switch Case Statement using Dictionary

def monday():
    return "monday"
def tuesday():
    return "tuesday"
def wednesday():
    return "wednesday"
def thursday():
    return "thursday"
def friday():
    return "friday"
def saturday():
    return "saturday"
def sunday():
    return "sunday"
def default():
    return "Incorrect day"

switcher = {
    1: monday,
    2: tuesday,
    3: wednesday,
    4: thursday,
    5: friday,
    6: saturday,
    7: sunday
    }

def switch(dayOfWeek):
    return switcher.get(dayOfWeek, default)()

print(switch(3))
print(switch(5))

 

Output:

wednesday
friday

 

Method 03) Using Classes

Along with the above methods to implement the switch case in python language, we can also use python classes to implement the switch case statement. An object constructor that has properties and methods is called a class.

So, let us see the example of performing a switch case using class by creating a switch method inside the python switch class.

Example:

class PythonSwitch:
    def day(self, dayOfWeek):

        default = "Incorrect day"

        return getattr(self, 'case_' + str(dayOfWeek), lambda: default)()

    def case_1(self):
        return "monday"

 

    def case_2(self):
        return "tuesday"

 

    def case_3(self):
        return "wednesday"

   

    def case_4(self):
       return "thursday"

 

    def case_5(self):
        return "friday"

 

    def case_7(self):
        return "saturday"
    
    def case_6(self):
        return "sunday"

   
my_switch = PythonSwitch()

print (my_switch.day(1))

print (my_switch.day(3))

 

Output:

monday
wednesday

 

If you need more help, you can get in touch with our expert python tutors.

Conclusion

In this article, we studied how to implement a Switch Case in Python programming. We have seen different methods to do the same. We also discussed code of each method. Each approach has its advantages and limitations, and the choice depends on the specific requirements of the program. Understanding these alternatives empowers Python developers to write cleaner and more efficient code, improving the readability and maintainability of their programs.

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Shivali Bhadaniya
I'm Shivali Bhadaniya, a computer engineer student and technical content writer, very enthusiastic to learn and explore new technologies and looking towards great opportunities. It is amazing for me to share my knowledge through my content to help curious minds.