Python doesn't provide a built-in switch statement, unlike other programming languages.
与其他编程语言不同,Python不提供内置的switch语句。
But there are scenarios, for which, using a switch statement is more optimized. To benefit ourselves to use a switch case, the following are the work-around.
但是在某些情况下,使用switch语句会得到更优化。 为了使自己受益于使用开关盒,以下是解决方法。
Consider the below example, of switch case in Java
考虑下面的例子, Java中的切换案例
public static String switchCase(int monthNum) {
String monthName = "Invalid Month";
switch (monthNum) {
case 1:
monthName = "January";
break;
case 2:
monthName = "February";
break;
case 3:
monthName = "March";
break;
case 4:
monthName = "April";
break;
case 5:
monthName = "May";
break;
case 6:
monthName = "June";
break;
case 7:
monthName = "July";
break;
case 8:
monthName = "August";
break;
case 9:
monthName = "September";
break;
case 10:
monthName = "October";
break;
case 11:
monthName = "November";
break;
case 12:
monthName = "December";
break;
default:
monthName = "Please provide the month number";
}
return monthName;
}
Now, by using the dictionary in python, we will be able to replicate similar behavior.
现在,通过使用python中的字典 ,我们将能够复制类似的行为。
def month(i):
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'
}
return switch.get(i, "Invalid month")
# printing
print(month(12))
print(month(13))
Output
输出量
December
Invalid month
In the above for values other than the ones mentioned in the switch, the code prints out "Invalid day of week". This is because we tell it to do so using the get() method of a dictionary.
在上面的值中,除了开关中提到的值以外,代码打印出“ Invalid day of week” 。 这是因为我们告诉它使用dictionary的get()方法这样做。
翻译自: https://www.includehelp.com/python/replacements-for-switch-statement.aspx