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 which makes accessible in one go.

How to implement switch statement in Python

The Pythonian way to implement switch statement is using powerful dictionary mappings feature, which 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 down 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=raw_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.

  1. If the match finds, it prints the associated value.
  2.  Else it prints a default string (‘Invalid Month’)  The default string helps implement the ‘default case’ of a switch statement.

Switch case statement comes handy when we try to form a menu driven/user-driven programs.
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 that visual compactness of any program and make it look more appealing and attractive.

Also, refer these for better understanding,

PHP Switch Case Statement

Creation, Addition, Removal, Modification of Dictionary in Python

Leave a Reply

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