DEV Community

hrishikesh1990
hrishikesh1990

Posted on • Originally published at flexiple.com

4 Ways to implement Python Switch Case Statement

In this short tutorial, we look at different methods to implement the switch case statement in Python. We look at what switch case is used for and the various methods to use this in Python.

Table of contents - Python Switch Case

What is a switch case used for?

The ‘switch case’ statement is like the ‘if… else’ statement but a cleaner and quicker way than ‘if… else’. It is present in languages like C++ or Java.

We use switch case specifically, when we need to run only a specific code block, and if the other code blocks do not satisfy the condition, they will be skipped. If this code block is checked manually, the complexity of code increases making it unfavorable. 

Using a switch case statement, one can test a variable for being one of the many possible values. The variable will follow the code for the particular value it takes. The significance of the switch case statement includes-

  1. Easy debugging
  2. Easy to read and understand
  3. Easy to maintain
  4. Easy to verify the values to be checked and handled

Python does not have a switch statement functionality. But there are ways to replace the switch statement functionality and make the programming easier and faster. This is possible as Python allows us to create our code snippets that work like Switch case statements in any other language. 

The ‘switch’ is  a control mechanism that tests the value stored in a variable. It executes the case statement corresponding to the switch statement. Thus, the ‘switch case’ statements control a flow in our program and ensures that our code is not cluttered by multiple ‘if’ statements. 

Before moving to the implementation of switch case statement in Python, let us understand the concept of switch case by the below example of the C++ code.

Syntax of switch case in C++

switch (expression)  {
    case constant1:
        // code to be executed if 
        // expression is equal to constant1;
        break;

    case constant2:
        // code to be executed if
        // expression is equal to constant2;
        break;
        .
        .
        .
    default:
        // code to be executed if
        // expression doesn't match any constant
}
Enter fullscreen mode Exit fullscreen mode

Example of switch case in C++

#include <iostream>
using namespace std;

int main() {
  int day = 4;
  switch (day) {
  case 1:
    cout << "Monday";
    break;
  case 2:
    cout << "Tuesday";
    break;
  case 3:
    cout << "Wednesday";
    break;
  case 4:
    cout << "Thursday";
    break;
  case 5:
    cout << "Friday";
    break;
  case 6:
    cout << "Saturday";
    break;
  case 7:
    cout << "Sunday";
    break;
  }
  return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output

Thursday
Enter fullscreen mode Exit fullscreen mode

In this case, we declare the variable day to be ‘4’. We then run different codes for the variable but it gets executed only for one particular condition where we declare case 4.
It then prints the value of the case, i.e. Thursday.

If you are also familiar with Java, here’s an example of switch case in Java

Syntax of switch case in Java

switch(expression)
{
   // The switch block has case statements whose values must be of the same type of expression
   case value1 :
   // Code statement to be executed
   break; // break is optional
   case value2 :
   // Code statement to be executed
   break; // break is optional
   // There can be several case statements
   // When none of the cases is true, a default statement is used, and no break is needed in the default case.
   default :
   // Code statement to be executed
}
Enter fullscreen mode Exit fullscreen mode

Example of switch case in Java

public class SwitchCaseExample1 {

   public static void main(String args[]){
     int num=2;
     switch(num+2)
     {
        case 1:
      System.out.println("Case1: Value is: "+num);
    case 2:
      System.out.println("Case2: Value is: "+num);
    case 3:
      System.out.println("Case3: Value is: "+num);
        default:
      System.out.println("Default: Value is: "+num);
      }
   }
}
Enter fullscreen mode Exit fullscreen mode

Output

Default: Value is: 2
Enter fullscreen mode Exit fullscreen mode

Now, after getting a fair understanding of switch case in C++ and Java, let us look at methods to implement switch case in Python.

Methods to implement switch case in Python

Using If elif else

The ‘if-elif’ is the shortcut for multiple if-else statements in Python. We start with an ‘if’ statement followed by ‘if-elif’ statements and in the end, we add the ‘else’ statement.

Syntax

if (condition):
    statement
elif (condition):
    statement
.
.
else:
    statement
Enter fullscreen mode Exit fullscreen mode

Example

# if elif statement example 

City= 'Bangalore'

if city == 'Delhi': 
    print("city is Delhi") 

elif city == "Hyderabad": 
    print("city is Hyderabad") 

elif city== "Bangalore": 
    print("city is Bangalore") 

else: 
    print("city isn't Bangalore, Delhi or Hyderabad")
Enter fullscreen mode Exit fullscreen mode

Output:

City is Bangalore
Enter fullscreen mode Exit fullscreen mode

Using Dictionary Mapping

In Python, the dictionary stores  groups of objects in memory using key-value pairs. For implementing the switch case statement, the key value of dictionary data type works like a ‘case’ in a switch case 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))
Enter fullscreen mode Exit fullscreen mode

Output

wednesday
friday
Enter fullscreen mode Exit fullscreen mode

Using Python classes

A class is an object constructor that has properties and methods. Classes in Python can be used to implement switch case statements. Given below is an example of using classes for the same.

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))
Enter fullscreen mode Exit fullscreen mode

Output

monday
wednesday
Enter fullscreen mode Exit fullscreen mode

Using Python Functions and Lambdas

In Python, we can use the functions and lambdas to implement switch case. Below is an example of the same.

Example

def zero():
        return 'zero'
def one():
        return 'one'
def indirect(i):
        switcher={
                0:zero,
                1:one,
                2:lambda:'two'
                }
        func=switcher.get(i,lambda :'Invalid')
        return func()
indirect(4)
Enter fullscreen mode Exit fullscreen mode

Output

Invalid
Enter fullscreen mode Exit fullscreen mode

Closing statement

Switch case is easy to use and implement. But Python does not have a in-built switch case function. In this tutorial, we saw that one can use If-elif-else, Dictionary Mapping or Classes to depict the switch case statement and increase efficiency.

Top comments (0)