How to Use Switch Case in Python

Switch Case Python

How to Use Switch Case in Python

Generally, programming aims to make a complex problem as simple as possible. In this way, switch cases can be very useful for executing specific code depending on the value or variable in question. In Python, there is no switch case, so we have to use an alternative. Find out how to implement switch case in Python today.

What is Switch Case?

Simply put, switch case statements allow your program to perform different functions depending on the value of a variable or statement. In this way, the switch case statement evaluates the value and compares the result with some pre-defined rules you’ve put in place. In each case, specific actions are to be performed if the value matches the switch case. You can also set a default code to be executed if none of the switch cases are matched.

While Python does not have a switch case, many other programming languages do. As such, let’s illustrate how a switch case works in C:

switch (expression) {

case value1: #code to execute if expression = value1

case value2: #code to execute if expression = value2

case value3: #code to execute if expression = value3

default: #code to execute if expression matches none of the above cases

Relatively simple, right? Unfortunately, we’ve got to do a little more work to implement this in Python. There are actually a few different ways to implement a function similar to switch case, so, let’s get into it.

How to Implement Switch Case Using If-elif-else Statements

One way is to use “if” and “else” statements to perform a specific function based on the input. This can actually be described in two ways. The first method looks like such:

color = 'Blue'

if color == 'Red':
print('color is Red')

elif color == 'Green':
print('color is Green')

elif color == 'Yellow':
print('color is Yellow')

elif color == 'Blue':
print('color is Blue')

print('Color is undetermined')

The input, or “color’, is tested against each of these conditions to see which one it matches. In this case, the color is clearly blue, so the expected output is ‘color is Blue’. And this is exactly what we see when we try out this code.

The switch case algorithm implemented with If-elif-else statements.

How to Implement Switch Case Using Dictionary Mapping

A dictionary is simply an unstructured set of data values and has key:value pairs. These are similar to headings in a spreadsheet, such as ‘Name’, ‘Height’ and ‘Weight’. Each key is paired with data values. In this way, we can use a sort of switch case function to return specific values from a dictionary. This is illustrated below:

def switch_case(argument):
switcher = {
"Red": "RED",
"Blue": "BLUE",
"Green": "GREEN"
return switcher.get(argument, "Invalid argument")

if__name__ =="__main__":
argument= "Green"

In this situation, we’re defining the function “switch_case” as a function that takes the argument.

The dictionary is defined as “switcher”, and contains key:value pairs. The keys represent capitalized color names, the values represent color names in all caps.

The value that corresponds to the argument key is returned from the dictionary by using the “get” function. Otherwise, the argument “invalid argument” is returned.

Since the input argument was “Green”, we get ‘GREEN” as the output.

The “if__name == “__main__”” line simply means that the code is only executed when running the script directly.

Dictionary mapping is used to implement switch case.

For a video walkthrough of this process, you can also check out the following video:

How to Implement Switch Case Using a Class

The last way to implement switch case in Python is by using a class. This is basically a template for making objects with defined attributes and methods. For example, a class called “ID” can have two attributes, “Height” and “Weight”, and methods for obtaining these values, like “get_height()” and “get_weight()”. For example, we can define the class as “switchcase” and implement the process as follows:

class switch_case:
    def month(self, year):
        default = "Incorrect month"

        return getattr(self, 'case_' + str(year), lambda: default)()

    def case_1(self):
        return "2001"

    def case_2(self):
        return "2002"

    def case_3(self):
        return "2003"

my_switch = switch_case()



Firstly, we define “switch_case” as a function that implements switch case.

Following this, the method is called “month()”, which takes the “year” parameter and calls the “month” method using different arguments, “1” and “3”. When the method is called with the argument “1”, it corresponds to the “case_1()” class method, outputting the result “2001”. When the argument of “3” is called, the output is the string value “2003”.

See the screenshot for how this code works in practice.

Switch Case Python
Switch case is implemented using a class.

Wrapping Up

While switch case isn’t explicitly included in Python, there are several ways to recreate this process. On the whole, these include using dictionary mapping, implementing a class function or using if-elif-else statements. In all cases, specific code is executed depending on the argument given, and specific values are returned depending on the switch statements.

Frequently Asked Questions

Which programming languages support switch case statements?

There are a lot of programming languages that support switch case statements, such as C, C++, Java, JavaScript, Ruby, Swift and Python. However, Python has no explicit switch case function, but the function can be implemented with the various methods described here.

Are switch case statements more efficient than if-else statements?

Not always. The efficiency of a switch case statement depends on the number of cases as well as how the code is being implemented. If there are only a few possible values for a given expression, if-else statements may be more efficient.

What happens if the value cannot be matched to any of the cases?

A default block of code is executed if none of the cases match the value in question.

What expressions can you use in a switch case statement?

It depends on the programming language you’re using, but it’s certainly possible to use expressions of types other than integers or string values, such as characters or enumerations.

Can you use multiple cases for the same code?

In most cases, yes. This can be helpful for when you want to use the same code for multiple values of an expression.

To top