In this tutorial, we’ll explain multiple ways to implement the Switch Case In Python. Before we get started, if you want to Conditional Statements in Python, please go through the following article: Conditional Statements in Python.

 

Switch Case In Python

Switch case is a powerful decision-making construct commonly used in modular programming. Unlike other programming languages, Python doesn’t provide a switch case instrument over the self. However, it has many other constructs like a dictionary, lambda function, and classes to write a custom implementation of switch case in python.

If you are keen to know why Python doesn’t have a switch case, then do refer the explanation at PEP 3103.

A Typical Switch Case in Java Programming

The switch case statement is a powerful programming feature that allows you to control the flow of your program based on the value of a variable or an expression. You can use it to execute different blocks of code, depending on the variable value during runtime. Here’s an example of a switch statement in Java.

Here’s how it works:

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

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

Switch Case using a Dictionary

It is simple to use a dictionary for implementing Switch Case in Python. Follow the below steps.

  • 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 functions beginning with the 0th index.
  • After that, write a switch() function accepting the day of the week as an argument.
  • The switch() calls the get() method on the dictionary object which returns the function matching the argument and invokes it simultaneously.

The output is as follows:

Switch Case using a Class

It is quite easy to use a class for implementing a Switch Case in Python. Let’s do it with an example.

  • In the below example, there is a PythonSwitch class which defines the switch() method.
  • It takes the day of the week as an argument, converts it to a string, and appends to the ‘case_’ literal. After that, the resultant string gets passed to the getattr() method.
  • The getattr() method returns a matching function available in the class.
  • If the string doesn’t find a match, then the getattr() returns the lambda function as default.
  • The class also has the definition of functions specific to different cases.

The output is as follows:

How to Implement Switch Case In Python

Leave a Comment