In this guide, we will explore five methods to simulate a Python Switch Case statement.

A switch case statement is a powerful tool in programming, providing developers full control over the program’s flow based on the outcomes of an expression or a variable’s value.

Switch cases are primarily used to execute different blocks of code in response to the results of an expression at runtime.

The program will follow a specific path if the result is one value, and another path if the result is a different value.

To provide a clear understanding of a switch case statement, let’s take a look at a Java example where we switch between months of the year and provide a default result if no match is found in the switch statement.

public static void switch_demo(String[] args) {

  int month = 7;
  String monthString;

  switch (month) {

    case 1:
      monthString = "January";
      break;

    case 2:
      monthString = "February";
      break;

    case 3:
      monthString = "March";
      break;

    case 4:
      monthString = "April";
      break;

    case 5:
      monthString = "May";
      break;

    case 6:
      monthString = "June";
      break;

    case 7:
      monthString = "July";
      break;

    case 8:
      monthString = "August";
      break;

    case 9:
      monthString = "September";
      break;

    case 10:
      monthString = "October";
      break;

    case 11:
      monthString = "November";
      break;

    case 12:
      monthString = "December";
      break;

    default:
      monthString = "Invalid month";
      break;

  }

  System.out.println(monthString);

}

This switch case statement works as follows:

  • Step 1: The compiler first generates a jump table for the switch statement.
  • Step 2: The switch statement evaluates the variable or the expression only once.
  • Step 3: The switch statement checks the evaluated result and makes a decision based on the result on which block of code to execute.

If no match is found, the default code will be executed.

In this example, if the default block of code is executed the result will be "Invalid month". However, since the month variable is initialized as 7, the output will be "July".

5 methods to Simulate a Python Switch Case Statement

Unlike PHP and Java, Python does not have built-in switch statements.

As a Python developer, you might be tempted to use if-else-if blocks, but a simulation of a switch case can be more efficient due to the jump table concept.

Here are five ways you can implement a switch-like behavior in Python:

Method 1: Using an if-else-if ladder

def switch():
    option = int(input("Enter your option from 1-3 to get the name of the month: "))

    if option == 1:
        result = "January"
 
    elif option == 2:
        result =  "February"
 
    elif option == 3:
        result = "March"
 
    else:
        result = "Incorrect option"

    print("The month is = ", result)
 
switch()

In the Python switch case example above, if we input 1, "January" will be printed in the console; if the input is 2, "February" is printed, and so forth.

Output

Enter your option from 1-3 to get the name of the month: 2
The month is =  February

Method 2: Simulating a switch case statement using a class

class PythonSwitchStatement:
    def switch(self, month):
        default = "Incorrect month"
        return getattr(self, 'case_' + str(month), lambda: default)()

    def case_1(self):
        return "January"

    def case_2(self):
        return "February"

    def case_3(self):
        return "March"

    def case_4(self):
        return "April"

    def case_5(self):
        return "May"

    def case_6(self):
        return "June"

    def case_7(self):
        return "July"


s = PythonSwitchStatement()

print(s.switch(3))
print(s.switch(4))
print(s.switch(10))


In this example, we first create a class called PythonSwitchStatement to define a switch() method. It also defines other functions for specific different cases.

The switch() method takes an argument month, converts it to a string, appends it to the case literal, and then passes it to the getattr() method, which returns the matching function available in the class.

If it doesn’t find a match, the getattr() method will return a lambda function as the default.

Output

March
April
Incorrect month

Method 3: Dictionary mapping replacement

def numbers_to_strings(argument):
    switcher = {
        0: "zero",
        1: "one",
        2: "two",
    }
    return switcher.get(argument, "nothing")

if __name__ == "__main__":
    argument = 1
    print(numbers_to_strings(argument))

In this example, we write a function to convert a number into a string. The get() method of the dictionary data type returns the value of the passed argument if it is present in the dictionary. Otherwise, the second argument will be assigned as the default value of the given argument.

Output

one

Method 4: Using a dictionary mapping to return value

b = {
    'a': 122,
    'b': 123,
    'c': 124,
    'd': 125
}

inp = input('Input a character: ')
print('The result for inp is: ', b.get(inp, -1))

In this example, we take user input to print our result; the -1 is the default value if there are no keys that match the input.

Output

Input a character: c
The result for inp is:  124

Method 5: Using dictionary mapping

def week(i):
    switcher = {
        0: 'Sunday',
        1: 'Monday',
        2: 'Tuesday',
        3: 'Wednesday',
        4: 'Thursday',
        5: 'Friday',
        6: 'Saturday'
    }
    return switcher.get(i, "Invalid day of the week")

print(week(1))  # Output: Monday
print(week(4))  # Output: Thursday
print(week(7))  # Output: Invalid day of the week

You can make calls to week() with different values to find out the day of the week.

For example, week(2) will output “Tuesday”, week(4) will output “Thursday”, and week(5.5) will output “Invalid day of the week”.

Output

Monday
Thursday
Invalid day of the week

Conclusion

Python does not have a built-in switch-case construct, but you can use dictionary mapping instead.

Python developers decided not to include the switch-case construct for a good reason.

Although many programmers and developers have been pushing for the inclusion of switch case constructs in Python, the existing alternatives serve the purpose just as effectively.