Switch Case in Python (Replacement)

Switch case statements

The if statement decides whether or not the condition is true. If the condition is true, the indented expression is evaluated; however, if the condition is false, the indented expression under else is evaluated. When we need to run multiple conditions, we can put as many elif conditions as we need between the if and else conditions. Long if statements that compare a variable to several integral values are replaced by switch case statements.

Switch case statements are a replacement for long if statements that compare a variable to several integral values.

  • The switch statement is a multiway branch statement.
  • It allows you to easily route execution to different parts of code based on the value of the expression.
  • A switch statement is a control statement that allows a value to change execution control.

The following are the benefits of using the Switch Case Statement in the program:

  • It is simpler to debug.
  • Anyone other than the programmer can read the program more easily.
  • It is simpler to understand and also to maintain.
  • It is easier to ensure that all values to be checked are handled.

Replacement of switch case statements in python

Python, unlike any other programming language we’ve used before, lacks a switch or case statement.

In this article let us look at the different methods to implement switch case statements in python:

  • Using dictionary Mapping
  • Using if-else statements
  • Using Classes

Switch Case in Python (Replacement)

Below are the ways to perform switch case in Python:

Method #1: Using Classes

Along with the methods described above for implementing the switch case statement in Python, we can also use Python classes.

A class is an object constructor that has properties and methods. Here we look at the below code of using a class to perform a switch case by creating a switch method within the Python switch class.

Approach:

  • Create a class say SwitchMonths
  • Create a function say month which accepts the month number as an argument
  • Give the default value to print if all the conditions fail
  • Get the attribute value by converting the month number to a string and concatenating with case_ (example case_3)
  • Create functions inside the class for each month
  • Create an object for the above SwitchMonths() class and store it in a variable
  • Call the month() function inside the class using the above object by passing the switch case number(month number) as an argument to it
  • Similarly, do the same for others.
  • The Exit of the Program.

Below is the implementation:

# Create a class say SwitchMonths
class SwitchMonths:
    # Create a function say month which accepts the month number as an argument
    def month(self, month):
        # Give the default value to print if all the conditions fails
        default = "Invalid Month"
        # get the attribute value by converting month number to string and concatenating with case_ (example case_3)
        return getattr(self, 'case_' + str(month), lambda: default)()
    # Create functions inside class for each month
    def case_1(self):
        return "january"

    def case_2(self):
        return "febrauary"

    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"

    def case_8(self):
        return "august"

# Create an object for the above SwitchMonths() class and store it in a variable
class_object = SwitchMonths()

# Call the month() function inside the class using the above 
# object by passing the switch case number(month number) as an argumet to it
print ("The 4th month is:", class_object.month(4))
# Similarly do the same for other
print ("The 7th month is:", class_object.month(7))

Output:

The 4th month is: april
The 7th month is: july

Method #2: Using if-else statements

If-elif is a shortcut for the if-else chain. We can use the if-elif statement and add an else statement at the end to perform if none of the if-elif statements above are true.

Syntax:

if (condition):
    statement
elif (condition):
    statement
.
.
else:
    statement

Approach:

  • Give the string(website name) as static input and store it in a variable.
  • Check if the given website name is Btechgeeks using the if conditional statement and == operator.
  • If it is true, the print “The given website is Btechgeeks”.
  • Else Again Check if the given website name is Sheetstips using the elif conditional statement
    and == operator.
  • If it is true, the print “The given website is Sheetstips”.
  • Else Again Check if the given website name is PythonPrograms using the elif conditional statement
    and == operator.
  • If it is true, the print “The given website is PythonPrograms”.
  • Else if all the above conditions fail then print some random acknowledgment.
    in an else conditional statement at the end.
  • The Exit of the Program.

Below is the implementation:

# Give the string(website name) as static input and store it in a variable.
gvn_website = 'PythonPrograms'

# Check if the given website name is Btechgeeks using the if conditional statement
# and == operator.
if gvn_website == 'Btechgeeks': 
    # If it is true, the print "The given website is Btechgeeks".
    print("The given website is Btechgeeks") 

# Else Again Check if the given website name is Sheetstips using the elif conditional statement
# and == operator.
elif gvn_website == "Sheetstips": 
    # If it is true, the print "The given website is Sheetstips".
    print("The given website is Sheetstips") 

# Else Again Check if the given website name is PythonPrograms using the elif conditional statement
# and == operator.
elif gvn_website == "PythonPrograms": 
    # If it is true, the print "The given website is PythonPrograms".
    print("The given website is PythonPrograms") 

# Else if all the above conditions fails then print some random acknowledgement 
# in a else conditional statement at the end
else: 
    print("Sorry! It is not a correct website")

Output:

The given website is PythonPrograms

Method #3: Using dictionary Mapping

The dictionary in Python uses key-value pairs to store groups of objects in memory. The key value of the dictionary data type acts as a ‘case’ in a switch case statement when implementing the switch case statement.

Below is the implementation:

def january():
    return "january"
def febrauary():
    return "febrauary"
def march():
    return "march"
def april():
    return "april"
def may():
    return "may"
def june():
    return "june"
def july():
    return "july"
def august():
    return "august"
def september():
    return "september"
def october():
    return "october"
def november():
    return "november"
def december():
    return "december"
def default():
    return "Invalid Month"
# Dictionary to store month values/numbers
switcherDict = {
    1: january,
    2: febrauary,
    3: march,
    4: april,
    5: may,
    6: june,
    7: july,
    8: august,
    9: september,
    10: october,
    11:november,
    12:december
    }

def switch(month): 
    return switcherDict.get(month, default)()

# Passing the value of the month to the switch() function to get month name
print("The 5th month is:", switch(5))
print("The 8th month is:", switch(8))

Output:

The 5th month is: may
The 8th month is: august