case/switch 语句的 Python 等效项是什么?

编程入门 行业动态 更新时间:2024-10-25 05:21:54
本文介绍了case/switch 语句的 Python 等效项是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想知道,是否有 Python 等效的 case 语句,例如 VB 或 C# 上可用的示例?

I'd like to know, is there a Python equivalent for the case statement such as the examples available on VB or C#?

推荐答案

虽然官方文档 很高兴不提供 switch,我看到了一个 解决方案使用字典.

While the official docs are happy not to provide switch, I have seen a solution using dictionaries.

例如:

# define the function blocks def zero(): print "You typed zero.\n" def sqr(): print "n is a perfect square\n" def even(): print "n is an even number\n" def prime(): print "n is a prime number\n" # map the inputs to the function blocks options = {0 : zero, 1 : sqr, 4 : sqr, 9 : sqr, 2 : even, 3 : prime, 5 : prime, 7 : prime, }

然后调用等效的 switch 块:

Then the equivalent switch block is invoked:

options[num]()

如果您严重依赖跌倒,这将开始分崩离析.

This begins to fall apart if you heavily depend on fall through.

更多推荐

case/switch 语句的 Python 等效项是什么?

本文发布于:2023-10-07 15:34:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1469790.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语句   case   switch   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!