Wednesday, August 21, 2024

Implement Switch Case in Python (match case & 3 alternatives)

 Implement Switch Case in Python (match case & 3 alternatives)

Most programming languages have a switch or case statement that lets you execute different blocks of code based on a variable. But does Python has a Switch statement? Now, Yes. In this article, we will discuss Switch Case in Python, a new feature called match case with an example, how to use it, and 3 others methods for implementing it with code. So, let’s get started!

What is a Switch statement?

In computer programming, a switch case statement is a kind of selection control system used to allow the value of the variable to change the control flow of program execution. The switch case statement is similar to the ‘if’ statement in any programming language.

The switch case statement is a replacement of the ‘if..else’ statement in any program when we know that the choices are going to be integer or character literals. The advantages of using the Switch Case Statement in the program are as given below:

  1. It is easier to debug.
  2. It is easier to read the program to anyone except the programmer.
  3. It is easier to understand and also easier to maintain.
  4. It is easier to verify all values that are to be checked are handled.
  5. It makes the code concise.

Need of Switch Case Statement

While programming, there are times when we need to execute a specific block of code depending on some other situation. If the given situation does not satisfy, the code block is skipped and does not get executed. If we check and apply these blocks of code manually without any format, the length and complexity of the code will increase. 

A switch statement is a useful tool for testing a variable against a number of possible values and executing different instructions based on the result. It is typically an improvement to add a switch statement to a program.

Does Python have a Switch statement?

Yes, Python does have a Switch case functionality. Since Python 3.10, we can now use a new syntax to implement this type of functionality with a match case. The match case statement allows users to implement code snippets exactly to switch cases.

It can be used to pass the variable to compare and the case statements can be used to define the commands to execute when one case matches.

How to use match case in Python?

The match-case statement consists of a series of case blocks, each of which specifies a pattern to match against the value. If a match is found, the corresponding code block is executed. If no match is found, an optional default block can be used to specify a default action.

Python added this feature with the 3.10 release in October of 2021 under "Structural Pattern Matching". It can be implemented in a very similar manner as we do in C, Java, or Javascript. The match case command is more easier and powerful.

It consists of 2 main components :

  1. The “match” keyword
  2. The case clause(s) with each condition/statement

A pattern that matches the variable, a condition that determines whether the pattern matches, and a series of statements that are to be executed if the pattern matches make up the case clause.

For numerous potential results of a given variable, we can create numerous case statements. A pattern must be matched in each case statement.

Let's look at how to implement it:

Syntax:

match subject:
    case <pattern_1>:
        <action_1>
    case <pattern_2>:
        <action_2>
    case <pattern_3>:
        <action_3>
    case _:
        <action_wildcard>

 

Example:

user_input = int(input("enter your lucky number between 1-5\n"))

match user_input:

        case 1:

         print( "you will have a new house")

        case 2:

         print( "you will receive good news ")

        case 3:

         print( "you will get a car")

        case 4:

         print( "you might face your fear this week")

        case 5:

         print( "you will get a pet")

 

Output:

enter your lucky number between 1-5
5
you will get a pet


Other Alternatives

We can also use 3 different replacements to implement a python switch case:

  1. If-elif-else
  2. Dictionary Mapping
  3. Using classes

Let us understand each python switch syntax one by one in detail below:

Method 01) If-elif-else

If-elif is the shortcut for the if-else if-else chain. We can use the if-elif statement and add the else statement at the end which is performed if none of the above if-elif statements is true. The if-elif chain allows you to handle multiple conditions inside one block.

Example:

# if-elif statement example 

fruit = 'Banana'

if fruit == 'Mango': 
    print("letter is Mango") 

elif fruit == "Grapes": 
    print("letter is Grapes") 

elif fruit == "Banana": 
    print("fruit is Banana") 

else: 
    print("fruit isn't Banana, Mango or Grapes") 

 

Output:

fruit is Banana


Method 02) Dictionary Mapping

If you know the basic python language then you must be familiar with a dictionary and its pattern of storing a group of objects in memory using key-value pairs. So, when we use the dictionary to replace the Switch case statement, the key value of the dictionary data type works as cases in a switch statement.

Example:

# Implement Python Switch Case Statement using Dictionary

def monday():
    return "monday"
def tuesday():
    return "tuesday"
def wednesday():
    return "wednesday"
def thursday():
    return "thursday"
def friday():
    return "friday"
def saturday():
    return "saturday"
def sunday():
    return "sunday"
def default():
    return "Incorrect day"

switcher = {
    1: monday,
    2: tuesday,
    3: wednesday,
    4: thursday,
    5: friday,
    6: saturday,
    7: sunday
    }

def switch(dayOfWeek):
    return switcher.get(dayOfWeek, default)()

print(switch(3))
print(switch(5))

 

Output:

wednesday
friday


Method 03) Using Classes

Along with the above methods to implement the switch case in python language, we can also use python classes to implement the switch case statement. An object constructor that has properties and methods is called a class.

So, let us see the example of performing a switch case using class by creating a switch method inside the python switch class.

Example:

class PythonSwitch:
    def day(self, dayOfWeek):

        default = "Incorrect day"

        return getattr(self, 'case_' + str(dayOfWeek), lambda: default)()

    def case_1(self):
        return "monday"

 

    def case_2(self):
        return "tuesday"

 

    def case_3(self):
        return "wednesday"

   

    def case_4(self):
       return "thursday"

 

    def case_5(self):
        return "friday"

 

    def case_7(self):
        return "saturday"
    
    def case_6(self):
        return "sunday"

   
my_switch = PythonSwitch()

print (my_switch.day(1))

print (my_switch.day(3))

 

Output:

monday
wednesday

..

Program Example

 ...


  1. Calculate Area of Rectangle:

    python
    length = float(input("Enter the length of the rectangle: ")) breadth = float(input("Enter the breadth of the rectangle: ")) area = length * breadth print(f"The area of the rectangle is {area}")
  2. Calculate Area of Circle:

    python
    import math radius = float(input("Enter the radius of the circle: ")) area = math.pi * (radius ** 2) print(f"The area of the circle is {area}")
  3. Calculate Total and Percentage of Marks:

    python
    name = input("Enter the student's name: ") marks = [] for i in range(5): mark = float(input(f"Enter the mark for subject {i+1}: ")) marks.append(mark) total = sum(marks) percentage = (total / 500) * 100 print(f"Total marks: {total}") print(f"Percentage: {percentage}%")
  4. Convert Feet to Inches:

    python
    feet = float(input("Enter the distance in feet: ")) inches = feet * 12 print(f"The distance in inches is {inches}")
  5. Convert Fahrenheit to Celsius:

    python
    fahrenheit = float(input("Enter temperature in Fahrenheit: ")) celsius = (fahrenheit - 32) * 5/9 print(f"The temperature in Celsius is {celsius}")
  6. Calculate Volume of Cylinder:

    python
    import math radius = float(input("Enter the radius of the cylinder: ")) height = float(input("Enter the height of the cylinder: ")) volume = math.pi * (radius ** 2) * height print(f"The volume of the cylinder is {volume}")

You can run these programs individually depending on which task you want to perform.

Python Files and Exceptions: Unit 9

  Table of contents Reading from a File Reading an Entire File File Paths Reading Line by Line Making a List of Lines from a File Working wi...