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?

<div><p><strong>Summary:</strong> 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 : </p>
<ul>
<li>Using a <a href="https://blog.finxter.com/python-dictionary/">Python Dictionary</a></li>
<li>Creating a Custom Switch <a href="https://blog.finxter.com/a-simple-example-for-python-objects-and-classes-video/">Class</a></li>
<li>Using <code>if-elif-else</code> Conditional Statements</li>
<li>Using a <a href="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/">Lambda Function</a></li>
</ul>
<p><strong>Problem:</strong> 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.</p>
<p><strong>Overview</strong>: 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 :</p>
<h2>What is a switch statement?</h2>
<p>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:</p>
<figure class="wp-block-image size-large is-style-default"><img src="https://blog.finxter.com/wp-content/uploads/2020/09/sitch-case-flowchart.gif" alt="" class="wp-image-13000" /><figcaption>fig: switch-case statement depicting program flow when nth case is TRUE </figcaption></figure>
<h2>switch vs if-else</h2>
<p> In a program that needs a complex set of nested <code>if</code> 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:</p>
<ol>
<li>If the number of cases is more, then switch-case statements are always more efficient and faster than <code>if-else</code>. </li>
<li>Switch case statements are more suited for fixed data values whereas <code>if-else</code> conditionals should be used in case of boolean values.</li>
<li>Switch statements check expressions based only on a single parameter / variable value whereas <code>if-else</code> conditional statements can be used to test expressions on a <a href="https://blog.finxter.com/daily-python-puzzle-range-indexing/">range </a>of values.</li>
</ol>
<p>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.</p>
<h2>Why does Python Not Have A “switch” Statement? </h2>
<figure class="wp-block-image"><img src="https://emojipedia-us.s3.dualstack.us-west-1.amazonaws.com/thumbs/160/facebook/92/thinking-face_1f914.png" alt="Thinking Face on Facebook 2.0" /></figure>
<p>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? </p>
<p>The answer is <strong>NO!!!</strong> Python does not need one. </p>
<ul>
<li>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 <a href="https://blog.finxter.com/python-dictionary/">dictionary</a>.</li>
<li>Furthermore, Python does not have a switch statement because none of the proposals that have been suggested so far have been deemed acceptable. </li>
</ul>
<p>#Note</p>
<p>Guido van Rossum says, “Some<a href="https://www.python.org/dev/peps/pep-3103/"> </a>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!!!) </p>
<p>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. </p>
<h2>Solutions</h2>
<p>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:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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
</pre>
<p>So without further delay, let the games begin!</p>
<h2>Method 1: Using A Dictionary</h2>
<p>A <a href="https://blog.finxter.com/python-dictionary/">dictionary</a> 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 (<em>Please follow the comments to get a better grip on the code)</em>:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 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))</pre>
<p><strong>Output:</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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</pre>
<p>Things to remember:</p>
<ul>
<li><code>get()</code> is an in-built function in python which returns the value for a specified key.</li>
<li><code>lambda</code> is a keyword in python which is used to define an anonymous function inside another function.</li>
</ul>
<p>I would strongly recommend you to go through these articles for an in-depth understanding of lambda and python dictionary functions and their usage:</p>
<ol>
<li><a href="https://blog.finxter.com/python-dictionary/">Link to learn about Python Dictionaries.</a></li>
<li><a href="https://blog.finxter.com/a-simple-introduction-of-the-lambda-function-in-python/#:~:text=A%20lambda%20function%20is%20an,values%20x%2By%2Bz%20.">Link to learn about Python Lambda Function. </a></li>
</ol>
<p>If you are not comfortable with the usage of <code>get()</code> and <code>lambda</code>, 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 :</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># 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))</pre>
<p><strong>Output</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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</pre>
<h2>Method 2: Creating A Switch Class</h2>
<p>Another workaround to use switch cases in our programs is to create a <a href="https://blog.finxter.com/a-simple-example-for-python-objects-and-classes-video/">class</a> with basic switch-case functionality defined within it. We can define each case within separate functions inside the class.</p>
<p>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): </p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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))</pre>
<p><strong>Output</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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</pre>
<h2>Method 3: A Quick Fix Using Lambda Function</h2>
<p>Though this method might not be the best in terms of code <a href="https://blog.finxter.com/complexity-of-python-operations/">complexities</a>, 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.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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))</pre>
<p><strong>Output</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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</pre>
<h2>Method 4: Using if-elif-else</h2>
<p>Sometimes it is always better to follow the <a href="https://app.finxter.com/learn/computer/science/">standard programming</a> constructs because they provide us the simplest solutions in most cases. Using the <a href="https://blog.finxter.com/if-then-else-in-one-line-python/">if-elif-else</a> might not be the exact replacement for a switch case but it provides a simpler construct and structure. Also, it avoids the problem of <a href="https://blog.finxter.com/python-one-line-exception-handling/">KeyError </a>if the matching case is not found.</p>
<p>Let us have a look at the following code to understand how we can use the if-elif-else conditionals to solve our problem:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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))</pre>
<p><strong>Output</strong></p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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</pre>
<h2>Conclusion</h2>
<p>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. </p>
<p>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<a href="https://blog.finxter.com/"> discussions and solutions </a>interesting then <a href="https://blog.finxter.com/subscribe">please subscribe and stay tuned</a> for more interesting articles in the future! </p>
<h2>Where to Go From Here?</h2>
<p>Enough theory, let’s get some practice!</p>
<p>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?</p>
<p><strong>Practice projects is how you sharpen your saw in coding!</strong></p>
<p>Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?</p>
<p>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.</p>
<p>Join my free webinar <a rel="noreferrer noopener" href="https://blog.finxter.com/webinar-freelancer/" target="_blank">“How to Build Your High-Income Skill Python”</a> and watch how I grew my coding business online and how you can, too—from the comfort of your own home.</p>
<p><a href="https://blog.finxter.com/webinar-freelancer/" target="_blank" rel="noreferrer noopener">Join the free webinar now!</a></p>
</div>


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



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016