Replacements For Switch Statement In Python?

Summary: Since switch-case statements are not a part of Python, you can use one of the following methods to create a switch-case construct in your code :


Problem: Given a selection control switch case scenario in Python; how to find a replacement for switch statement since Python does not have a provision for switch-case statements.

Overview: Before we discuss the solutions to our problem, we must have a clear picture of the switch-case statement itself. To understand the switch statements let us answer a few questions:

What’s a Switch Statement?

In programming languages like C, C++, C#, and Java, switch is a conditional statement used to test the value of a variable and then compare this value with several cases. Once the match case is found, the block of code defined within the matched case is executed. Let us have a look at the following flowchart to visualize the working principle of switch case:

fig: switch-case statement depicting program flow when nth case is TRUE

Switch vs If-Else

In a program that needs a complex set of nested if statements, a switch statement is always a better and more efficient alternative in such situations. Following are some of the key factors which should be taken into consideration while deciding whether to use switch case or if-else statements in the code:

  1. If the number of cases is more, then switch-case statements are always more efficient and faster than if-else.
  2. Switch case statements are more suited for fixed data values whereas if-else conditionals should be used in case of boolean values.
  3. Switch statements check expressions based only on a single parameter / variable value whereas if-else conditional statements can be used to test expressions on a range of values.

There are a few other factors governing the proper usage of the two statements. However, that is beyond the scope of this article, as we are going to focus on the replacements for switch statements in Python in this article. Now that brings us to the next and probably the most important question.

Why does Python Not Have A “switch” Statement?

Thinking Face on Facebook 2.0

You might have been wondering all the while, why are we even proposing a solution for replacing the switch statement in python. Does python not have a “switch” statement?

The answer is NO!!! Python does not need one.

  • Most programming languages have switch-case statements because they lack proper mapping constructs. While in Python, we have well-defined mapping constructs and you can easily have a mapping table in the form of a python dictionary.
  • Furthermore, Python does not have a switch statement because none of the proposals that have been suggested so far have been deemed acceptable.

Note: Guido van Rossum, Python’s creator, says, “Some kind of switch statement is found in many languages and it is not unreasonable to expect that its addition to Python will allow us to write up certain code more cleanly and efficiently than before.”

So this might indicate that in the future we might find that the switch statement is implemented in Python, though it is quite unlikely to happen anytime soon. (But the future is full of unpredictabilities!!!)

Now that we have an overview of the switch-statement, let us find out the alternatives for switch statements that can be used in Python.

Solutions

Let us discuss how we can create alternatives to switch cases and ask the user to select an option for the operation they want to perform. Based on the users’ choice the output shall be displayed. Here’s a sample output of what we want to achieve:

Press 1: Addition
Press 2: Subtraction
Press 3: Multiplication
Press 4: Division

Enter your choice: 1
Enter 1st Number: 500
Enter 2nd Number: 2000
Answer =  2500

So without further delay, let the games begin!

Method 1: Using A Dictionary

A dictionary in python stores items in the form of key-value pairs such that a certain value maps to a specific key. Let us have a look at the following code to understand how we can use a dictionary as an alternative to switch case and solve our problem (Please follow the comments to get a better grip on the code):

# The default case when no case matches
def default(a, b):
    return "Invalid Entry!"


def switch(option, a, b):
    # create the dictionary and switch-cases / choices
    return {
        '1': lambda a, b: a + b,
        '2': lambda a, b: a - b,
        '3': lambda a, b: a * b,
        '4': lambda a, b: a / b,
    }.get(option, default)(a, b)


# User Menu Prompt
print('''
Press 1: Addition
Press 2: Subtraction
Press 3: Multiplication
Press 4: Division
''')
# Accept User Entry
choice = input("Enter your choice: ")
x = int(input("Enter 1st Number: "))
y = int(input("Enter 2nd Number: "))
# Pass Values Entered by User to evaluate and then Print the output
print(switch(choice, x, y))

Output:

Press 1: Addition
Press 2: Subtraction
Press 3: Multiplication
Press 4: Division

Enter your choice: 1
Enter 1st Number: 15
Enter 2nd Number: 50
Answer =  65

You can try this yourself in our interactive code shell!

Exercise: Press different keys and try the different options!

Things to remember:

  • get() is an in-built function in python which returns the value for a specified key.
  • lambda is a keyword in python which is used to define an anonymous function inside another function.

I would strongly recommend you to go through these articles for an in-depth understanding of lambda and python dictionary functions and their usage:

  1. Learn about Python Dictionaries.
  2. Learn about Python Lambda Function.

If you are not comfortable with the usage of get() and lambda, I have a solution for you too. Have a look at the following code which might be a little lengthier and more complex in terms of time and memory usage but is certainly easier to grasp:

# Addition
def choice1(x, y):
    return x + y


# Subtraction
def choice2(x, y):
    return x - y


# Multiplication
def choice3(x, y):
    return x * y


# Division
def choice4(x, y):
    return x / y


def switch(option, a, b):
    try:
        # create the dictionary and switch-cases / choices
        return {
            '1': choice1,
            '2': choice2,
            '3': choice3,
            '4': choice4,
        }[choice](x, y)
    except KeyError:
        # Default Case
        return 'Invalid Entry!'


# User Menu Prompt
print('''
Press 1: Addition
Press 2: Subtraction
Press 3: Multiplication
Press 4: Division
''')
# Accept User Entry
choice = input("Enter your choice: ")
x = int(input("Enter 1st Number: "))
y = int(input("Enter 2nd Number: "))
# Pass Values Entered by User to evaluate and then Print the output
print("Answer = ", switch(choice, x, y))

Output

Press 1: Addition
Press 2: Subtraction
Press 3: Multiplication
Press 4: Division

Enter your choice: 2
Enter 1st Number: 20
Enter 2nd Number: 10
Answer =  10

Method 2: Creating A Switch Class

Another workaround to use switch cases in our programs is to create a class with basic switch-case functionality defined within it. We can define each case within separate functions inside the class.

Let us have a look at the following program to understand how we can create a switch-case class (As always, I request you to read the comments within the code to get a better grip):

class SwitchCase:
    def case(self, option, x, y):
        default = "Invalid Entry!"
        # lambda invokes the default case
        # getattr() is used to invoke the function choice that the user wants to evaluate 
        return getattr(self, 'choice' + str(option), lambda x, y: default)(x, y)

    # Addition
    def choice1(self, x, y):
        return x + y

    # Subtraction
    def choice2(self, x, y):
        return x - y

    # Multiplication
    def choice3(self, x, y):
        return x * y

    # Division
    def choice4(self, x, y):
        return x / y

    # Default Case
    def default(self, x, y):
        return "Invalid Entry!"


# creating the SwitchCase class object
switch = SwitchCase()
# User Menu Prompt
print('''
Press 1: Addition
Press 2: Subtraction
Press 3: Multiplication
Press 4: Division
''')
# Accept User Entry
option = input("Enter your choice: ")
x = int(input("Enter 1st Number: "))
y = int(input("Enter 2nd Number: "))
# Pass Values Entered by User to evaluate and then Print the output
print("Answer = ", switch.case(option, x, y))

Output

Press 1: Addition
Press 2: Subtraction
Press 3: Multiplication
Press 4: Division

Enter your choice: 4
Enter 1st Number: 24
Enter 2nd Number: 4
Answer = 6.0

Method 3: A Quick Fix Using Lambda Function

Though this method might not be the best in terms of code complexities, however, it might come in handy in situations where you want to use a function once and then throw it away after the purpose is served. Also, this method displays how long pieces of codes can be minimized, hence this method makes a worthy entry into the list of our proposed solutions.

var = (lambda x, y, c:
       x + y if c == '1' else
       x - y if c == '2' else
       x * y if c == '3' else
       x / y if c == '4' else
       'Invalid Entry!')

# User Menu Prompt
print('''
Press 1: Addition
Press 2: Subtraction
Press 3: Multiplication
Press 4: Division
''')
# Accept User Entry
option = input("Enter your choice: ")
x = int(input("Enter 1st Number: "))
y = int(input("Enter 2nd Number: "))
print(var(x, y, option))

Output

Press 1: Addition
Press 2: Subtraction
Press 3: Multiplication
Press 4: Division

Enter your choice: 4
Enter 1st Number: 500
Enter 2nd Number: 25
20.0

Method 4: Using if-elif-else

Sometimes it is always better to follow the standard programming constructs because they provide us the simplest solutions in most cases. Using the if-elif-else might not be the exact replacement for a switch case but it provides a simpler construct and structure. Also, it avoids the problem of KeyError if the matching case is not found.

Let us have a look at the following code to understand how we can use the if-elif-else conditionals to solve our problem:

def func(choice, a, b):
    if choice == '1':
        return a + b
    elif choice == '2':
        return a - b
    elif choice == '3':
        return a * b
    elif choice == '4':
        return a / b
    else:
        return 'Invalid Entry!'


# User Menu Prompt
print('''
Press 1: Addition
Press 2: Subtraction
Press 3: Multiplication
Press 4: Division
''')
# Accept User Entry
option = input("Enter your choice: ")
x = int(input("Enter 1st Number: "))
y = int(input("Enter 2nd Number: "))
print("Answer = ", func(option, x, y))

Output

Press 1: Addition
Press 2: Subtraction
Press 3: Multiplication
Press 4: Division

Enter your choice: 1
Enter 1st Number: 500
Enter 2nd Number: 2000
Answer =  2500

Conclusion

In this article, we discussed how we can replace the switch case statements in our python code using python dictionary mapping or by creating a class or by applying a quick fix using a python lambda function. Having said that, the best way to implement switches in python is to use a dictionary that maps the key and value pairs.

I hope you enjoyed reading this article and after reading it you can use an alternative to switch-case in your code with ease. If you find these discussions and solutions interesting then please subscribe and stay tuned for more interesting articles in the future!

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!