Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Replacements For Switch Statement In Python?

#1
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 is a switch statement?


In programming languages like C, C++, C#, Java, etc 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 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

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. Link to learn about Python Dictionaries.
  2. Link to 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!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And 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?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become 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.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!



https://www.sickgaming.net/blog/2020/09/...in-python/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] Python’s NameError: name ‘xxx’ is not defined — How to Fix This Stupid Bug? xSicKxBot 0 7 10-16-2020, 10:30 PM
Last Post: xSicKxBot
  [Tut] Python IndentationError: unexpected indent (How to Fix This Stupid Bug) xSicKxBot 0 15 10-10-2020, 08:24 PM
Last Post: xSicKxBot
  [Tut] Yield Keyword in Python – A Simple Illustrated Guide xSicKxBot 0 16 10-09-2020, 06:13 PM
Last Post: xSicKxBot
  [Tut] Python Reverse List with Slicing — An Illustrated Guide xSicKxBot 0 28 10-02-2020, 04:24 AM
Last Post: xSicKxBot
  [Tut] How to Remove Duplicates From a Python List While Preserving Order? xSicKxBot 0 29 10-01-2020, 02:21 AM
Last Post: xSicKxBot
  [Tut] How To Update A Key In A Dictionary In Python If The Key Doesn’t Exist? xSicKxBot 0 31 09-29-2020, 09:02 PM
Last Post: xSicKxBot
  [Tut] How to Get the Last Element of a Python List? xSicKxBot 0 32 09-28-2020, 02:36 AM
Last Post: xSicKxBot
  [Tut] How To Format A String That Contains Curly Braces In Python? xSicKxBot 0 30 09-25-2020, 07:51 PM
Last Post: xSicKxBot
  [Tut] Python One Line Dictionary xSicKxBot 0 35 09-21-2020, 05:58 PM
Last Post: xSicKxBot
  [Tut] Python Import Error (ModuleNotFoundError) xSicKxBot 0 32 09-20-2020, 04:15 PM
Last Post: xSicKxBot

Forum Jump:

Become a Patron!
[-]
Upcoming Events

[-]
Latest Threads
AppleInsider - Lowest iPad Pro prices: s...
Last Post: xSicKxBot
Today 03:19 PM
» Replies: 0
» Views: 1
Microsoft - CVP Tom McGuinness: Top take...
Last Post: xSicKxBot
Today 03:19 PM
» Replies: 0
» Views: 1
News - Nintendo First Revealed The Switc...
Last Post: xSicKxBot
Today 03:19 PM
» Replies: 0
» Views: 1
News - Luigi Can Be Unlocked As A Secret...
Last Post: xSicKxBot
Today 03:19 PM
» Replies: 0
» Views: 1
Xbox Wire - Announcing Details for Xbox ...
Last Post: xSicKxBot
Today 01:19 PM
» Replies: 0
» Views: 2
News - Report: China-owned mobile studio...
Last Post: xSicKxBot
Today 01:19 PM
» Replies: 0
» Views: 3
News - Get a job: Join Insomniac Games a...
Last Post: xSicKxBot
Today 01:19 PM
» Replies: 0
» Views: 3
Microsoft - The importance of bringing b...
Last Post: xSicKxBot
Today 08:18 AM
» Replies: 0
» Views: 4
News - Party-Based RPG Battle Hunters Pu...
Last Post: xSicKxBot
Today 08:18 AM
» Replies: 0
» Views: 4
(Indie Deal) PlugInDigital & Kalypso Str...
Last Post: xSicKxBot
Today 03:29 AM
» Replies: 0
» Views: 5

[-]
Twitter

[-]
Sponsored
Get the Deal of the Week at RefurBees.com

Copyright © SickGaming.net 2012-2020