Please note, this is a STATIC archive of website www.simplilearn.com from 27 Mar 2023, cach3.com does not collect or store any user information, there is no "phishing" involved.

Switch cases are one of the most important and powerful techniques that programmers use for controlling the flow of the program. It is the best replacement for a long if-else ladder. It’s a boon when you have to write a long chain of if-else statements, which often clutters the entire program. It provides a cleaner and faster way to control the flow of the program. 

For example, if you want to build a simple calculator that takes in the type of operation as input along with two numbers, instead of using an if-else ladder to find out whether the input operation type is addition, multiplication, subtraction, or division, you can simply pass the operation as a character to the switch argument. And depending upon the cases that you have defined, it will return the output automatically. 

Working of a Switch Case

When you define a switch statement in any programming language, it usually follows a general pattern to implement it. It allows you to select one or more blocks of case statements according to the switch parameter. It works by evaluating the switch statement, compares the result of the evaluation with the values defined in each of the case blocks, and tries to find matches. 

If it finds a match, then the code defined inside the case block is executed and the values are returned. Often, it is also possible to define a default block along with all the cases. This is useful if the switch statement evaluates to a value that does not match with any of the catch blocks. In such a case, the default block is executed.

Python Training Course

Learn Data Operations in PythonExplore Course
Python Training Course

The general syntax of a switch-case statement is - 

switch(arg)
{
case 1: Statement if arg = 1;
break;
case 2: Statement if arg = 2;
break;
::
case n: Statement if arg = n;
break;
default: Statement if arg doesn't match any
}

This is a general syntax that every switch-case-supporting programming language follows.

Switch in Python

Unfortunately, Python does not support the conventional switch-case statements that other languages provide. However, there are several workarounds or replacements that can be used in the place of traditional switch statements. And in fact, these are much easier and intuitive than the traditional ones. You will look at all of them in this guide.

There are several workarounds such as a dictionary, lambda functions, classes, etc. that can efficiently replace a switch statement and makes the code more transparent, easy-to-understand, and meticulous, at the same time. So without any further ado, let’s start discussing each of these methods one-by-one.

Replacements of Switch in Python

In this section of the tutorial, you will look at three different ways to implement a switch in Python. These are very easy and intuitive and use simple Python concepts like functions, classes, dictionaries, etc. to implement them. Let’s have a look at them one at a time.

1. Implementing Switch Using Dictionary Mapping

Dictionaries in Python are simple key-value pairs that are widely used for a variety of purposes. You can use dictionaries to implement a workaround of a switch in Python. Let’s try to create a simple calculator using a Dictionary mapped switch workaround. Have a look at the code below.

def calculator(operation, value1, value2):

   switcher = {

       "*": value1*value2,

       "/": value1/value2,

       "+": value1+value2,

       "-": value1-value2 

   }

   return switcher.get(operation, "Invalid Operation! Please try again.")

print(calculator("+", 5, 10))

print(calculator("*", 5, 10))

print(calculator("#", 5, 10))

The program above has created a simple function that takes as input an operation as a string, and two numbers as integers. Here, there is a defined switcher dictionary where you have mapped the four operations, with their respective calculations on the numbers. Finally, you saw the use of the get method on the dictionary to input the key value (operation) as the argument along with a default value, if none of the operations in the keys matches with the input operation. The get method takes the input argument and compares it with all the keys in the dictionary and returns the corresponding value. Let’s check the output.

DictionaryMapping

You can see that the program has returned the correct outputs for both operations. The program had defined the last operation as an invalid one, hence, it returns the default return value of the dictionary.

2. Using Lambda Functions for Dynamic Operations

In Python, Lambda functions are very popular. They are anonymous functions (functions without a name) that are used to perform operations in a single line or expression. You can leverage Lambda functions in Python and use them along with dictionary mappings to create switch workarounds that require doing complex operations in the case blocks. 

Now, try to implement the same calculator example but with Lambda functions.

def calculator(operation, value1, value2):

   switcher = {

       "*": lambda v1, v2: v1*v2,

       "/": lambda v1, v2: v1/v2,

       "+": lambda v1, v2: v1+v2,

       "-": lambda v1, v2: v1-v2,

   }

   return switcher.get(operation)(value1, value2)

print(calculator("+", 5, 10))

print(calculator("*", 5, 10))

Here, this demo has used the lambda functions to perform calculations. Hence, you need to pass the parameters to the lambda functions, along with the key with the get method on the switcher dictionary. Now, verify the output.

DynamicOperations

You can see that our program returns the appropriate output. Lambda functions are useful when you want to define complex calculations or operations to be returned when a match occurs with the keys of the switcher dictionaries.

Free Course: Programming with Python

Learn the Basics of Programming with PythonEnroll Now
Free Course: Programming with Python

3. Implementing Switch in Python using Classes

In Python, you use classes and objects to implement object-oriented programming. It is also possible to use classes to implement switch cases in Python, and are quite easy as well. Now, look at this with the help of another program.

class Switcher:

   def switch(self, day):

       default = "Oops! Invalid Day. Please try again!"

       return getattr(self, 'Case_' + str(day), lambda: default)()

   def Case_1(self):

       return "Hello! It's Monday"

   def Case_2(self):

       return "Hello! It's Tuesday"

   def Case_3(self):

       return "Hello! It's Wednesday"

   def Case_4(self):

       return "Hello! It's Thursday"

   def Case_5(self):

       return "Hello! It's Friday"

   def Case_6(self):

       return "Hello! It's Saturday"

   def Case_7(self):

       return "Hello! It's Sunday"

day = Switcher()

print(day.switch(6))

print(day.switch(0))

print(day.switch(4))

In the above program, your aim was to create a calendar where you need to input the day number from 1 to 7, and it should return the corresponding day of the week. For that, you must create a simple class called Switcher, and inside that, there are several functions that depict the cases.  There is the master function which will take as input the day, and either return a valid function according to the match using the getattr method. If a match does not happen, it will return the default string.

Finally, you must create an object of the Switcher class and used it to call the master function which, in turn, returns the appropriate values. Moving on, check out the output.

/PythonusingClasses

You can see that the correct outputs have been returned and in the second invoke since a match does not happen, it returns the default string value that was defined in the switch method. 

Looking forward to making a move to the programming field? Take up the Python Training Course and begin your career as a professional Python programmer

Wrapping Up!

In this comprehensive guide, you have seen the basics of switch-case statements along with their general syntax. Although Python does not support switch statements, you saw how to use several alternatives to implement them on your own. This article discussed dictionary-mapped implementation using functions, and the same with a lambda function to implement the case blocks. Finally, it also explored a class-based approach to create switch workarounds in Python.

We hope that this intuitive guide will help you to get hands-on with Switch in Python. Have any questions for us? Leave them as comments below, our experts will answer them for you ASAP!

Happy Learning!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.