Computer Science Related Others Courses AvailableThe Best Codder.blogspot.com
Posts

Switch Case in Python (Replacement)

 

Switch Case in Python (Replacement)


What is the replacement of Switch Case in Python?

Unlike every other programming language we have used before, Python does not have a switch or case statement. To get around this fact, we use dictionary mapping.

Method 1:  Switch Case implement in Python using Dictionary Mapping

In Python, a dictionary is an unordered collection of data values that can be used to store data values. Unlike other data types, which can only include a single value per element, dictionaries can also contain a key: value pair.
The key value of the dictionary data type functions as cases in a switch statement when we use the dictionary to replace the Switch case statement.

# Function to convert number into string
# Switcher is dictionary data type here
def numbers_to_strings(argument):
    switcher = {
        0: "zero",
        1: "one",
        2: "two",
    }
 
    # get() method of dictionary data type returns
    # value of passed argument if it is present
    # in dictionary otherwise second argument will
    # be assigned as default value of passed argument
    return switcher.get(argument, "nothing")
 
# Driver program
if __name__ == "__main__":
    argument=0
    print (numbers_to_strings(argument))

Method 2: Switch Case implement in Python using if-else

The if-else is another method to implement switch case replacement. It is used to determine whether a specific statement or block of statements will be performed or not, i.e., whether a block of statements will be executed if a specific condition is true or not.

bike = 'Yamaha'
 
if fruit == 'Hero':
    print("letter is Hero")
 
elif fruit == "Suzuki":
    print("letter is Suzuki")
 
elif fruit == "Yamaha":
    print("fruit is Yamaha")
 
else:
    print("Please choose correct answer")

Method 3: Switch Case implement in Python using Class

In this method, we are using a class to create a switch method inside the python switch class in Python.

class Python_Switch:
    def day(self, month):
 
        default = "Incorrect day"
 
        return getattr(self, 'case_' + str(month), lambda: default)()
 
    def case_1(self):
        return "Jan"
 
    def case_2(self):
        return "Feb"
 
    def case_3(self):
        return "Mar"
 
 
my_switch = Python_Switch()
 
print(my_switch.day(1))
 
print(my_switch.day(3))

Output: 

Jan
mar

Switch Case in Python

In Python 3.10 and after that, Python will support this by using match in place of switch:

def number_to_string(argument):
    match argument:
        case 0:
            return "zero"
        case 1:
            return "one"
        case 2:
            return "two"
        case default:
            return "something"
 
 
if __name__ = "__main__":
    argument = 0
    number_to_string(argument)

Post a Comment

© Python . The Best Codder All rights reserved. Distributed by