Menu Close

Python 没有 Switch Case 语句 , Switch Case语句是如何实现的?

什么是switch语句?

switch 语句是一种多路分支语句,它将变量的值与 case 语句中指定的值进行比较。

Python 语言没有 switch 语句。

Python使用字典映射在Python中实现Switch Case

例如

function(argument){
    switch(argument) {
        case 0:
            return "This is Case Zero";
        case 1:
            return " This is Case One";
        case 2:
            return " This is Case Two ";
        default:
            return "nothing";
    };
};

以上算法的Python语言的实现

例1.Switch Case 语句的实现

def SwitchExample(argument):
    switcher = {
        0: " This is Case Zero ",
        1: " This is Case One ",
        2: " This is Case Two ",
    }
    return switcher.get(argument, "nothing")


if __name__ == "__main__":
    argument = 1
    print (SwitchExample(argument))

结果

This is Case One

 

 

除教程外,本网站大部分文章来自互联网,如果有内容冒犯到你,请联系我们删除!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

Leave the field below empty!

Posted in Python教程

Related Posts