Python Switch – Learn approaches to implement switch case statement

Switch-case statements are a strong tool for control in programming.

Switch-case statement may be a powerful programming feature that permits you control the flow of your program supported the worth of a variable or an expression.

The core Python doesn’t support switch statements which are available in other popular languages like C/C++ or Java.

So in this article, we are going to see a workaround of how we can implement Python switch statements on our own.python switch

Keeping you updated with latest technology trends, Join TechVidvan on Telegram

Python Switch Approaches

To implement the switch statement in Python, we will be using two approaches.

1. Python Switch-Case Statement

First, let us understand how a switch-case statement works.

If you have come from a C/C++ or Java background, then you might already know how switch case looks like.

Here, is a simple C++ program that makes use of a switch-case statement.

Code:

#include <iostream>
using namespace std;

int main()
{
   char operator;
   float num1, num2;

   cout << "Enter an operator (+, -, *, /): ";
   cin >> operator;

   cout << "Enter two numbers: ";
   cin >> num1 >> num2;

switch (operator)
{
       case '+':
           cout << num1 << " + " << num2 << " = " << num1+num2;
           break;
       case '-':
           cout << num1 << " - " << num2 << " = " << num1-num2;
           break;
       case '*':
           cout << num1 << " * " << num2 << " = " << num1*num2;
           break;
       case '/':
           cout << num1 << " / " << num2 << " = " << num1/num2;
           break;
       default:
           // operator is doesn't match any case constant (+, -, *, /)
           cout << "Error! Invalid operator";
           break;
}

   return 0;
}

The switch statement allows us to execute different operations for different possible values of a single variable.

We can define multiple cases for a switch variable.

Switch case for Python was proposed but it was rejected.

Check this link for a full discussion, Source code: PEP 3103 – A switch case

Since Python doesn’t have this switch statement, we can implement the switch in Python using dictionary mappings.

Implementing Python Switch using Functions

In python switch, the first way to implement things is the if-elif ladder.

But here we are going to create a function and use the Python dictionary to get the functionality similar to switch-case statements.

1. Simple Dictionary Mapping

Let’s implement a function that will take a number as an argument and return us the day of the week.

Code:

def days_of_week(day):

    switcher ={
        1: 'Monday',
        2: 'Tuesday',
        3: 'Wednesday',
        4: 'Thursday',
        5: 'Friday',
        6: 'Saturday',
        7: 'Sunday'
    }

    return switcher.get(day,"Invalid day ")


print( days_of_week(5))
print( days_of_week(2))
print( days_of_week(7))
print( days_of_week(10))

Output:

Friday
Tuesday
Sunday
Invalid day

Here in python switch, we created the function days_of_week() and it has a switcher dictionary that works like a switch where its keys are the case to match and its values are what we want to get returned.

The get() method of dictionary returns us the value of the key from the dictionary and if the key does not exist then it returns the second argument.

2. Using Lambdas for Dynamic Functions

In python switch, Lambda functions are anonymous functions that can perform operations on a single expression.

Using lambdas functions, we can calculate different things based on the input.

Python lambda syntax :

lambda arguments : expression

Code:

def calculate(n1, n2, operator):

    switcher ={
        '+': lambda n1,n2: n1+n2,
        '-': lambda n1,n2: n1-n2,
        '*': lambda n1,n2: n1*n2,
        '/': lambda n1,n2: n1/n2,

    }

    return switcher.get(operator)(n1,n2)


print( calculate(10,20,'+'))
print( calculate(10,20,'-'))
print( calculate(10,20,'*'))
print( calculate(10,20,'/'))

Output:

30
-10
200
0.5

Implementing Python Switch-Case using Classes

It is also easy to implement a switch case with class.

Let’s see an example program.

In the below example we call the switch() method which takes the day of the week and appends it to a string.

Here, we use getattr() to match method name and in the end, we call the method to get the desired output.

Code:

class SwitchCase:

    def switch(self, dayOfWeek):
        default = "Invalid day"
        return getattr(self, 'case_' + str(dayOfWeek), lambda: default)()

    def case_1(self):
        return "Monday"

    def case_2(self):
        return "Tuesday"

    def case_3(self):
        return "Wednesday"

    def case_4(self):
        return "Thursday"

    def case_5(self):
        return "Friday"

    def case_6(self):
        return "Saturday"

    def case_7(self):
        return "Sunday"

day = SwitchCase()

print(day.switch(1))
print(day.switch(0))
print(day.switch(3))

Output:

Monday
Invalid day
Wednesday

Summary

Hence we conclude that even though Python does not support the switch-case decision-making statements, we can implement them on our own.

We saw two types of implementations in Python switch, first, we used dictionary mapping to implement switch with functions and then implemented the switch using a class.

This was all about TechVidvan’s Python Switch article.

1 Response

  1. simon88 says:

    Dear sirs or madam,
    For the last (n1,n2) in your code:

    def calculate(n1, n2, operator):
    switcher ={
    ‘+’: lambda n1,n2: n1+n2,
    ‘-‘: lambda n1,n2: n1-n2,
    ‘*’: lambda n1,n2: n1*n2,
    ‘/’: lambda n1,n2: n1/n2,
    }
    return switcher.get(operator)(n1,n2)

    Could your explain why between “get(operator)” and “(n1, n2)” do not have any sign to show what the code will do here?
    Thank you very much

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.