Why does python not support switch statement?

1. What is switch?

The syntax format of the switch statement is as follows:

switch(expression){
    
    
	case value1:
		//语句
		break; //可选
	case value2:
		//语句
		break; //可选
	default: //可选
		//语句
}

Use a flow chart to represent:
Insert image description here

Its usage is: if the value of the switch statement satisfies which case, the corresponding code block will be executed. When a break is encountered during execution, it will jump out, otherwise it will continue to execute the next case branch. Usually a default is placed at the end.
Most languages ​​provide switch statements or something similar. For example, in static languages ​​such as C/C++/Java/Go, they all support switch-case structures.
The advantage of the switch statement is that it supports a "single condition and multiple branches" selection structure. Compared with the binary selection structure of if-else, it will be more concise and clearer in some cases.
But in python, we can't see switch-case or similar syntax structures.

2. Why doesn’t Python support switch?

Someone once made some proposals (PEP-275 and PEP-3103) to introduce switch syntax to python. However, there was no consensus on "whether and how to conduct range testing", which ultimately led to the abortion of the proposal.

3. switch-case alternatives

There is a FAQ in the official documentation that gives several suggestions and tells us several switch-case alternatives:

  • Use if-elif-else conditional judgment statements
  • Use a dictionary. Map case values ​​to called functions
  • Use the built-in getattr() to retrieve the specific object call method

3.1. Example 1: Implementation using if conditional judgment statement

#判断今天是星期几,打印对应课程
from datetime import datetime
def taskforMath():
    print("今天上数学课")

def taskforChinese():
    print("今天上语文课")

def taskforRest():
    print("今天休息")

def taskforArt():
    print("今天上美术课")

def taskforDance():
    print("今天上舞蹈课")

def taskforDefault():
    print("输入错误啦。。。。")

# 获取今天是星期几,返回int
dayofWeek=datetime.today().weekday()
# ——————————————————使用if-elif-else方式替代switch————————————————————
if dayofWeek==0:
    taskforMath()
elif dayofWeek==1:
    taskforChinese()
elif dayofWeek in [2,5,6]:
    taskforRest()
elif dayofWeek==3:
    taskforArt()
elif dayofWeek==4:
    taskforDance()
else:
    taskforDefault()

3.2. Example 2: Implementation using dictionary

#判断今天是星期几,打印对应课程
from datetime import datetime
def taskforMath():
    print("今天上数学课")

def taskforChinese():
    print("今天上语文课")

def taskforRest():
    print("今天休息")

def taskforArt():
    print("今天上美术课")

def taskforDance():
    print("今天上舞蹈课")

def taskforDefault():
    print("输入错误啦。。。。")
# 获取今天是星期几,返回int类型
dayofWeek=datetime.today().weekday()

# -------------------使用字典方式替代switch,创建星期与课程的映射关系-----------------
dict={
    
    "星期一":taskforMath,"星期二":taskforChinese,"星期三":taskforRest,"星期四":taskforArt,"星期五":taskforDance,"星期六":taskforRest,"星期日":taskforRest}
todayis=list(dict.keys())[dayofWeek]
# dict[todayis]() # 这种写法无法在这一步设置默认打印,需要将默认写进dict中
dict.get(todayis,taskforDefault)()

3.3. Example 3: Using built-in getattr()

#判断今天是星期几,打印对应课程
from datetime import datetime
class A:
    def taskforMath(self):
        print("今天上数学课")

    def taskforChinese(self):
        print("今天上语文课")

    def taskforRest(self):
        print("今天休息")

    def taskforArt(self):
        print("今天上美术课")

    def taskforDance(self):
        print("今天上舞蹈课")

    def taskforDefault(self):
        print("输入错误啦。。。。")

# 获取今天是星期几,返回int
dayofWeek=datetime.today().weekday()
a=A()
task=["taskforMath","taskforChinese","taskforRest","taskforArt","taskforDance","taskforRest","taskforRest","taskforDefault"]
getattr(a,task[dayofWeek])()

Supongo que te gusta

Origin blog.csdn.net/u011090984/article/details/130482231
Recomendado
Clasificación