case/switch 语句的 Python 等效项是什么? [英] What is the Python equivalent for a case/switch statement?

查看:85
本文介绍了case/switch 语句的 Python 等效项是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to know, is there a Python equivalent for the case statement such as the examples available on VB.net 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 等效项是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆