Оператор выбора варианта питон

Switch Case Statement in Python (Alternatives)

In this Python tutorial, we will understand how to use the switch case statement in Python with examples.

Until, Python version 3.10, Python does not support the use of switch case statement like other programming languages. However, there are multiple ways in Python using which we can replicate the same functionality.

So, in this tutorial, we will discuss the following methods to execute switch case statement in Python.

  • Using Dictionary Mapping
  • Using if-elif-else Method
  • Using Functions & Lambda
  • Using Classes & Objects
  • Using match statement in Python 3.10

Does Python have a switch case statement?

Most of the languages support the case statement. But, in Python, there is no switch case statement by default if you are using Python version 3.9 or lower. However, we can make our own functions that we can use as an alternative to the case statement.

Note: Please note that we can use a switch case statement in Python 3.10 by using match statement.

Hence, in this article, I will explain how you can create functions in Python that you can use as the switch case statement.

Читайте также:  End of life java

How to use switch case statement in Python?

Basically, in Python, there are 5 ways to use the switch case statement in Python:

  • Using Dictionary Mapping Method
  • Using if-elif-else Method
  • Using Class Method
  • Using Python Functions and Lambdas
  • Using match in Python 3.10

Let us discuss each of these methods in detail using examples.

Method 1: Switch case in Python using Dictionary Mapping

In the first method, we will understand how to implement a switch case statement in Python using dictionary mapping.

For this, first, we will define a dictionary with case name as the key and case execution as the value. However, the value can either be a function or a set of statements.

To execute the statement or function for a particular case, you can use the get() method of the Python dictionary.

Now let us see an example. Consider the following python code.

dict= < 1: 'Sunday', 2: 'Monday', 3: 'Tuesday', 4: 'Wednesday', 5: 'Thursday', 6: 'Friday', 7: 'Saturday' >print('Entered Number is 2. Day of the week is:',dict.get(2))

We have created a dictionary to use the case statement. The numbers from 1 to 7 will be the different cases and we will print the day of the week corresponding to those numbers.

We have used the get() function to get the value for the supplied key.

Case statement dictionary Python

Method 2: Switch case in Python using if-elif-else Method

Another method to replicate the switch case statement in Python is by using multiple if-else statements. To use multiple if-else in Python, we use the concept of the if-elif-else statement.

The main idea behind this method as a switch case statement can be understood with the example below.

if == : elif == : elif == : . . . elif == : else:

With this approach, we will use multiple if-elif statements to check the occurrence of a particular event. And based on this, we can execute or return the result.

Here is an example of implementing this method.

Suppose you want to print the month’s name of a year according to a specified number. For example, 1 to 12 represents the months of the year from January to December.

In this case, you may want to use the case statement. But, let us see how we can implement this with the help of an if-else statement.

def printMonth(num): if num == 1: month =' January' elif num == 2: month = 'February' elif num == 3: month = 'March' elif num == 4: month= 'April' elif num == 5: month= 'May' elif num == 6: month = 'June' elif num == 7: month = 'July' elif num == 8: month = 'August' elif num == 9: month= 'September' elif num == 10: month= 'October' elif num == 11: month= 'November' elif num == 12: month= 'December' return month print('Month is:', printMonth(10))
  • In the above function, we are assigning the name of the month in every if block according to the specified number.

Simple case statement in Python

You can see that we supplied the number 10 as the input and the function returned October. Similarly, we have defined all the cases from 1 to 12 in the function.

In this way, you can use the if-else statement to implement the switch case statement in Python.

Method 3: Switch case in Python using Functions & Lambda

In this section, we will understand how to use user-defined functions or lambda functions in Python to replicate the switch case.

Let us understand this execution in Python using an example.

def day_1(): return 'Sunday' def day_2(): return 'Monday' def day_3(): return 'Tuesday' def day_4(): return 'Wednesday' def day_5(): return 'Thurday' def day_6(): return 'Saturday' def switch(num): dict= < 1: day_1, 2: day_2, 3: day_3, 4: day_4, 5: day_5, 6: day_6, 7: lambda :'Saturday' >result = dict.get(num, lambda:'Invalid Day') return result() print(' The number is: 1 and the day is:',switch(1)) print(' The number is: 7 and the day is:',switch(7)) print(' The number is: 8 and the day is:',switch(8))
  • In the above example, we utilized the dictionary mapping method to replicate the switch case condition in Python.
  • However, for the result of each case, we either defined a user-defined function or a lambda function.
  • At last, we combined all the execution in the switch() function for execution.

Switch case statement in Python using functions

From the above example, we can observe that, for each number, it is returning a day name as a result.

Method 4: Switch case in Python using Classes & Objects

We can also implement the switch case functionality in Python by using the concept of classes and objects.

  • In this approach, first, we will create a class for the switch function and define all the methods or functions inside the class for every case.
  • Later, we will create an object of this class and call a function of this class and specify the case value as the argument.

Here is a sample Python code for this implementation.

class Switch: # Defining a function for every case def case_1(self): print('January') def case_2(self): print('February') def case_3(self): print('March') def case_4(self): print('April') def case_5(self): print('May') def case_6(self): print('June') def case_7(self): print('July') def case_8(self): print('August') def case_9(self): print('September') def case_10(self): print('October') def case_11(self): print('November') def case_12(self): print('December') # Defining a function to decide which function to call def circle(self, cases): method = 'case_' + str(cases) return getattr(self, method)() # Declaring an object switcher= Switch() # Calling the switch case method switcher.circle(12)

switch case python with arguments

  • In the above code, the circle function will decide which case is invoked and which function to call.
  • We are concatenating the two strings case_ and str(cases) to make the function name. Then we will pass this string to the getattr() function.
  • The getattr() function takes two arguments.
    • First is the object name, which is self in our case.
    • Second is the name of the attribute of the object that we want to return. This attribute name will be defined as a string.

    In this way, we can use classes and objects to implement the switch case functionality in Python.

    Method 5: Switch case in Python using match statement in Python 3.10

    In all the previous sections, we covered methods for Python version 3.9 or lower. However, if you have Python version 3.10, we can directly implement the switch case statement using the match statement in Python.

    Here is the basic syntax of using the match statement in Python.

    match var_name: case val_1: python_statment_1 case val_2: python_statement_2 case val_3: python_statement_3

    The use of a match statement is the same as the use of the switch-case statement in other programming languages. However, in Python, in place switch, we need to use the match keyword.

    Next, let us check an example of using the match statement in Python for implementing switch-case.

    day = input("Enter a number from 1 to 7: ") match day: case "1": print("Sunday") case "2": print("Monday") case "3": print("Tuesday") case "4": print("Wednesday") case "5": print("Thursday") case "6": print("Friday") case "7": print("Saturday") case _: print("Please enter a valid number")

    In the above example, we utilized the match-case statement to print the day of the week based on an input number.

    Here is the sample execution of the above Python program.

    match-case in Python

    Python switch case statement best practices

    In this section, I will explain to you the best practices to implement the switch case functionality in Python for various techniques that we discussed above.

    • If you have very few cases to check you should use the if-else method for implementing the switch case functionality.
    • This is because this method is very fast in performance if you have a few if-else statements. Also, it is not very difficult to write a few statements.
    • But, if you have a large number of cases to check, you should use the dictionary mapping method. It is better than the if-else method in a large number of cases.
    • If you want to check a range as a single case, you have to use the if-else method.
    • You should avoid the use of classes and object methods for implementing the switch case functionality. This is because it is a difficult and complex method for implementation. Also, it is not much efficient in terms of performance.

    These are some points that you should keep in your mind while selecting an appropriate method for implementing the switch case statement in Python.

    You may like the following Python tutorials:

    So, in this article, we have discussed the implementation of switch case statement in Python with the help of 5 different ways. Here is the list of methods that we covered.

    • Using Dictionary Mapping
    • Using if-elif-else Method
    • Using Functions & Lambda
    • Using Classes & Objects
    • Using match statement in Python 3.10

    I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

    Источник

Оцените статью