Implementing Switch Case functions in Python

Switch Case statement in Python
Switch Case statement in Python

Switch case statement introduces control flow in our programme and ensures that our code is not cluttered by multiple ‘if’ statements.

In that case, Switch-case statement is a quicker and powerful programming feature that allows them to control the flow of their programme based on the value of a variable or an expression. They can use it to execute different blocks of code, depending on the variable value during runtime. In general, the switch is a control mechanism that tests the value stored in a variable and executes the corresponding case statements.

Hence, our code looks meticulous and transparent to viewers. It is a wonderful programming feature that
programmers use to implement the control flow in their code. Switch case statement works by comparing the
values specified in the case statements with variables in our code.

In this article, we will see how we can implement the switch case functions in Python Programming languages. Unlike other programming languages like Java, C++, Python does not have a switch case function. Along with this, we will see how to work a loophole for python switch case functions. Let us discuss the different ways of implementation for Python Switch case functions.

Python does not have a simple switch-case construct. Coming from a Java or C++ background, you may find this to be a bit different, as Java and C++ have an in-built switch statement, Here we may be surprised to know that Python language doesn’t have one. And for this we may be tempted to use a series of if-else-if blocks, using an if a condition for each case of your switch statement. However, because of the jump table, a switch statement is much faster than an if-else-if ladder. Instead of evaluating each condition sequentially, it only has to look up the evaluated variable/expression once and directly jump to the appropriate branch of code to execute it.

We can clearly understand it by taking examples of how it can be used in C++ and Java so in C++ or Java we use the switch case functions:

Here’s how it works:

  • The compiler generates a jump table for the switch case statement
  • The switch variable/expression is evaluated once
  • Switch statement looks up the evaluated variable/expression in the jump table and directly decides which code block to execute.
  • If no match is found, then the code under default case is executed.

In the above example, depending on the value of the variable month, a different message will be displayed in the standard output. In this case, since the month=8, ‘August’ will be printed in the standard.

Solutions for Python Switch-Case function:

Dictionary Mapping: As we know that Python does not have a simple switch-case statement here one way out would be to implement an if-elif-else ladder. Rather, we can use a dictionary to map cases to their functionality, this Pythonic way to implement a switch statement will use the powerful dictionary mappings. If someone is familiar with other programming languages, then he/she must be knowing that the dictionary uses key-value pairs to store a group of objects in memory. When we are using a dictionary as an alternative to switch-case statements, keys of the key-value pair work as a case. 

Here’s the Python implementation of the switch case functions. In this example, we create a dictionary named switcher to store all the switch-like cases.

 Here, in this example, when we pass an argument to the switch_demo function, it is looked up against the switcher dictionary mapping. If a match is found, the associated value is printed, else a default string (‘Invalid Month’) is printed. The default string helps implement the ‘default case’ of a switch statement.

A switcher is a dictionary that performs this mapping.

As we can see it clearly that for values other than the one which we mention in the switcher, it prints out “Invalid Month”. This is because we tell it to do so using the get( ) method of a dictionary.

Dictionary mapping using Python functions:

Here we got it more interesting. The values of a Python dictionary can be of any data type. So we don’t have to confine ourself for using constants (integers, strings), we can also use function names and lambdas as values.

For example, we can also implement the above switch statement by creating a dictionary of function names as values. It is simple to use this for implementing the Python switch case statement. We have to follow some steps for it .

  • First, define individual functions for every case.
  • Make sure there is a function/method to handle the default case.
  • Next, make a dictionary object and store each of the function beginning with the 0th index.
  • After that, write a switch() function accepting number to months as arguments.
  • The switch() calls the get() method on the dictionary object which returns the function matching the argument and invokes it simultaneously.

 In this case, switcher is a dictionary of function names, and not strings.

Dictionary mapping using Python Classes:

We can also use Python classes as an alternative way to implementing switch-case statements. A class is an object constructor that has properties and methods. Let us understand this further with the help of the same above example. It is quite easy to use a class for implementing the Python switch case statement. Let’s do it with the example.

Based on the passed argument, the in-built getattr() function will retrieve object methods with the particular name. In the above example, we have used two things: keyword lambda and getattr() method.

  • We use the lambda keyword to define an anonymous function in Python. Lambda keyword invokes the default function when a user enters invalid input.
  • getattr() method is used to invoke a function in Python.

 Advantages of Pythonic Appoach:

Since we can change Python dictionaries during runtime (add, remove or update key-value pairs), so we can easily change our every switch statement on the fly. Here’s an example:

Conclusion: Switch case is a very useful programming construct that not only provides better performance than an if-else statement but also leaves us with a more manageable code.In this article, we have learned about switch-case functions, after that we  discuss what are the alternatives of these switch-case functions, and how to use them.Hence as explained above,we conclude that even Python does not have an in-built switch case function, but we can always use these alternatives (like using dictionary mapping instead placing switch case)to implement them on our own way.Here we saw two types of implementation in Python, first, we used dictionary mapping to implement switch with functions and then implemented the switch using a class so by these alternative we make our code look neat and clean and get better performance.

To read more about Python, click here.

By Mayank Mishra