Switch Case In Python

Switch case is like if else conditions, in the switch case statements we create cases that if the given condition doesn’t meet its requirement so it will switch to the next case, and if it matches with the given condition so we use break statement there and the execution of code will be stopped.  

The switch case statements are rarely used but it also plays a vital role in programming. Switch case statements are used in many programming languages like C, JAVA, and PHP but unfortunately, we are not able to use this functionality in Python,

Sadly python does not have switch case statements but the good news is that there are some alternate ways we can use as the replacement of switch case statements in python, like if else conditions, dictionary mapping, and using python classes and functions.

So let’s start the tutorial with the first way.

1) By using If-else Condition

def Month(number):
    if number == 1:
        month =' January'
    elif number == 2:
        month = 'February'
    elif number == 3:
        month = 'March'
    elif number == 4:
        month= 'April'
    elif number == 5:
        month= 'May'
    elif number == 6:
        month = 'June'
    elif number == 7:
        month = 'July'
    elif number == 8:
        month = 'August'
    elif number == 9:
        month= 'September'
    elif number == 10:
        month= 'October'
    elif number == 11:
        month= 'November'
    elif number == 12:
        month= 'December'
    return month
print('Month is:', Month(7))

Code Explanation

In the above code, we defined a function with if and else if conditions. In the function, we passed “number” as a parameter, and then we created if condition that states that if the parameter “number” is equal to 1 then print the name of the first month of the year which is January, means we assigned January to “number  1”.

We followed the same steps for the rest of the months just changed the numbers.

The above code will print the month name according to the number we will provide, if the number is 1 so January will be printed if it is 2 then February will be printed and like this, the other conditions will work till the number 12.

check out the results below.

Output

 month is: July

2) By using Dictionary Mapping

def switch():
               value1=int(input("enter first value:"))
               value2=int(input("enter 2nd value:"))
   print("press 1 for addition, 2 for sub, 3 for multiply and 4 for division")
option=int(input("your option:"))
def add():
               result=value1+value2
               print(result)

def sub():
               result=value1-value2
               print(result)

def mul():
               result=value1*value2
               print(result)

def dev():
               result=value1/value2
               print(result)

               dictionary={
               1 : add,
               2 : sub,
               3 : mul,
               4 : div
               }
               dictionary.get(option)()
               
switch() 

Code Explanation

In the above code, we defined a function then we declared 2 variables “value1” and “value2”. We stored the user input values in those variables then we printed a text after that we again declared a variable “option” and stored the user input value in it.

We created 4 functions (add, sub, mul, and div) in each function we applied different operations using value1 and value2 variables.

 At last, we created a dictionary and stored the declared functions with keys in it, and called the main function which we defined at the start of the code.

Basically, the above code will perform the operation of addition, subtraction, multiplication, and division according to user input.

Output

3) By using Classes and Functions

class Weather():
  def weather(current, season):
    default = "not that Season!"
    return getattr(current, 'season_' + str(season), lambda:default)()
  
  def season1(current):
    return "season is Spring"
  def season2(current):
    return "season is Summer"
  def season3(current):
    return "season is Autumn"
  def season4(current):
    return "season is Winter"
  
this_season = Weather()
print (this_season.weather(1))
print (this_season.weather(10))

Code Explanation

In the above code, we used classes alternatively as the replacement of switch case statements.

First, we declared a class then we defined a function and passed “current” and “season” as a parameter, and we declared a default value as well.

We returned the getattr function for invoking a function call. in the getattr function, we passed parameters and lambda which will return an unknown function and that function will print the default value if the user enters an invalid value.

Then we defined 4 functions that will print the season name and last we just called the functions.

Output

season is Spring
not that Season

Conclusion

In this tutorial, we talked about the alternative ways which we can use as a replacement of switch case statements. We saw the if else conditions then we used the dictionary mapping method, in the end, we discussed the Python class and functions with example.

That’s all for today hope you like the tutorial if you have any queries regarding this article so feel free to contact us below. Thanks for reading.

Leave a Comment