Switch Case In Python – (Replacement)
As we all know, that every other language has a switch control or case-control structure. In this tutorial, we will see how to use switch case-control statements in Python by the implicit definition of the structure.
To get started we must be familiar with dictionary mapping in Python.
Mapping in mathematics is an operation that associates each element of a given set (the domain) with one or more elements of a second set (the range). Likewise, dictionary mapping is a way of connecting the keys with the values that are mapping all of them to establish a link that is accessible in one go.
How to implement switch statement in Python
The Pythonian way to implement switch statement is using a powerful dictionary mappings feature, which is also known as associative arrays, that provides simple one-to-one key-value mappings.
Here’s an implementation of the above switch statement in Python. In the example below, we create a dictionary named switch
to store all the switch-like cases.
def switch_demo(argument): switch = { 1: "January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "August", 9: "September", 10: "October", 11: "November", 12: "December" } print (switch.get(argument, "Invalid month")) #main x=int(input()) switch_demo(x)
In the above example, when you pass an argument to the switch_demo
function, it is looked up against the switch
dictionary mapping.
- If the match is found, it prints the associated value.
- Otherwise, it prints a default string (‘Invalid Month’) The default string helps implement the ‘default case’ of a switch statement.
The Switch case statement comes in handy when we try to form a menu-driven/user-driven program.
The user provides the choices as input. The function runs in accordance with the choice entered.
It’s highly useful in case there is a requirement for pattern matching. Using Switch statements ensures the visual compactness of any program and makes it look more appealing and attractive.
Leave a Reply