作者:麦叔
来源:麦叔编程
❝
学过其他编程语言的同学肯定发现了我们Python语言中竟然没有"很常见"的switch/case关键字,更别提对应的语法结构了。既然没有,有些时候又需要用,那只能自己写一个"fake_switch"了。
❞
python没有?" class="syl-page-img" style="border: none; margin-top: 20px; max-width: 715px; height: auto;">以Java的switch用法进行参照(摘自菜鸟教程)
public class Test { public static void main(String args[]){ char grade = 'C'; switch(grade) { case 'A' : System.out.println("优秀"); break; case 'B' : case 'C' : System.out.println("良好"); break; case 'D' : System.out.println("及格"); break; case 'F' : System.out.println("你需要再努力努力"); break; default : System.out.println("未知等级"); } System.out.println("你的等级是 " + grade); }}用if-elif-else代替def fake_switch_1(grade:str) -> str: if grade == "A": return "优秀" elif grade == "B" or grade == "C": return "良好" elif grade == "D": return "及格" elif grade == "F": return "你需要再努力努力" else: return "未知等级" # 调用显示结果 print(fake_switch_1("A"))print(fake_switch_1("B"))print(fake_switch_1("C"))print(fake_switch_1("D"))print(fake_switch_1("F"))print(fake_switch_1("Z"))运行代码:
优秀良好良好及格你需要再努力努力未知等级用字典(dict)+ try...except...语句代替def fake_swith_2(grade:str) -> str: level = { "A":"优秀", "B":"良好", "C":"良好", "D":"及格", "F":"你需要再努力努力", } try: g = level[grade] except Exception: g = "未知等级" return g # 调用显示结果 print(fake_switch_2("A"))print(fake_switch_2("B"))print(fake_switch_2("C"))print(fake_switch_2("D"))print(fake_switch_2("F"))print(fake_switch_2("Z"))运行代码:
优秀良好良好及格你需要再努力努力未知等级match...case...语句(Python3.10以后引入)这个算是属于python自己的switch/case语句了,其用法基本和其他语言的switch/case语句一样。
def fake_switch_3(grade:str) -> str: match grade: case "A": return "优秀" case "B": return "良好" case "C": return "良好" case "D": return "及格" case "F": return "你需要再努力努力" case _: return "未知等级" print(fake_switch_3("A")) print(fake_switch_3("B")) print(fake_switch_3("C")) print(fake_switch_3("D")) print(fake_switch_3("F")) print(fake_switch_3("Z"))运行代码:
优秀良好良好及格你需要再努力努力未知等级总结❝
最后一段的case _:类似于 C 和 Java 中的default:,当匹配不到字符时就会执行该语句下的表达式。
❞
我自己感觉用Python字典(dict)+ try...except...的形式去实现switch/case的功能会让代码显得更整洁更pythonic。在维护这段代码时只要注重字典(dict)中的键值对和try语句中defult的值,而不用太去关注逻辑判断上是否会出问题,在某种意义上讲,这可能还是超越switch/case的地方。
「小伙伴们,这三种选择结构,你们喜欢哪种呢?请在评论区留言,加上喜欢的原因,那就更好了。」
关于python为什么没有switch/case语句
python没有?" class="syl-page-img" style="border: none; margin-top: 20px; max-width: 715px; height: auto;">根据上图表面,前期Python之父Guido是不希望引入switch/case规则的,他曾说“Python is fine without a switch statement”。但十五年后,Guido却引入了match/case规则,难道match/case逃不出真香定律?
相关帖子DA内容精选
|


雷达卡





京公网安备 11010802022788号







