Python Equivalent to the Case/Switch Statement
Python does not provide a dedicated syntax for case/switch statements like other programming languages. However, there are several alternative approaches to achieve similar functionality.
Using Pattern Matching (Python 3.10 and above)
From version 3.10 onwards, Python introduced pattern matching.它允许您匹配不同的模式并执行相应的代码块。
def http_error(status): 比赛状态: 案例400: 返回“不良请求” 案例404: 返回“未找到” 案例418: 返回“我是茶壶” 案例_:#默认情况 返回“ Internet出现问题”def http_error(status): match status: case 400: return "Bad request" case 404: return "Not found" case 418: return "I'm a teapot" case _: # Default case return "Something's wrong with the internet"3.10之前,一个常见的解决方法是将词典用于将dictionaries映射到相应的函数块。
#定义功能块 def Zero(): 打印(“您输入零。\ n”) def sqr(): 打印(“ n是一个完美的正方形\ n”) def evev(): 打印(“ n是偶数\ n”) def prime(): 打印(“ n是素数\ n”) #映射输入到功能块 选项= {0:零, 1:SQR, 4:SQR, 9:SQR, 2:甚至 3:Prime, 5:Prime, 7:Prime} #调用等效开关块 选项[num]()
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3