/  Technology   /  Replacement for switch statements in Python?
Replacement for switch statements in Python?

Replacement for switch statements in Python?

 

Python has no concept of switch statements, unlike other programming languages. So we use dictionary mapping to implement switch statements in Python. 

 

Let’s discuss dictionary mapping now. Consider a dictionary named switch_equivalent with the following keys and values.

Example:

switch_equivalent = {0: "Zero", 1: "One", 2: "Two"}

 Here we defined a function named fun(), which has a dictionary switch_equivalent and returns the fetched value for the corresponding argument(key) passed into it.

 

Example:

def funn(number):
   switch_equivalent = {
      0: "Zero", 
      1: "One", 
      2: "Two"
   }
   return switch_equivalent.get(number, "null")


if __name__ == "__main__":
   number=2
   print (fun(number))

Output:

The dictionary method get() returns the value of the passed argument(key) if it is present in the dictionary, else the second argument will be assigned as the default value of the passed argument.

 

Below is the C++equivalent code for the above Python code for better understanding.

Example:

using  namespace std;

string fun(int number)
{
   switch(number)
   {
      case 0:
         return "zero";
      case 1:
         return "one";
      case 2:
         return "two";
      default:
         return "null";
   };
};

int main()
{
   int argument = 0
   cout << fun(number);
   return 0;
}

 

The Python 3.10 version has got many new updates, one of which being the implementation of switch case statements in Python. It’s called the match case

Syntax:

 match variable_name:

case ‘pattern1’ : 

       //statement 1

case ‘pattern2’ : 

       //statement 2

   …………...
case ‘pattern n’ : 
       //statement n

The match case consists of three main parts:

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

Below is the equivalent match case code we discussed above. 

Example:

def f(x):
   match x:
      case 1:
         return "One"
      case 2:
         return "Two"
      case 3:
         return "Three"

 

Leave a comment