如何在python中实现switch case ..?

时间:2018-01-11 06:11:38

标签: python python-3.x

检查以下代码:

var = input("enter a number between 1 and 12")
def switch_demo(var):
    switcher = {
                1: "Jan" 
                2: "Feb" 
                3: "March"
                4: "April" 
                5: "May" 
                6: "June" 
                7: "July" 
                8: "August" 
                9: "Sept" 
                10: "Oct" 
                11: "Nov" 
                12: "Dec"
    }
    print switcher.get(var,"Invalid Month")

我在第5行收到语法错误 我该如何解决错误?

2 个答案:

答案 0 :(得分:5)

修复你的错误

您需要在每个项目的末尾添加逗号:

public function onAjaxVariations() {
    $this->controller->pageCycle();
    // $this->page['service'] will be available
} 

工作计划:

 1: "Jan", 
 2: "Feb",

更简单的解决方案

您应该查看def switch_demo(var): switcher = { 1: "Jan", 2: "Feb", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "August", 9: "Sept", 10: "Oct", 11: "Nov", 12: "Dec" } return switcher.get(var,"Invalid Month") var = int(input("enter a number between 1 and 12")) print(switch_demo(var)) 模块。 它已经提供了所有月份名称:

calendar

答案 1 :(得分:-1)

Switch case是一个非常强大的编程控制工具,因为我们可以控制它用它来执行不同的代码块。 在python中,您可以使用字典方法和发布的代码来实现它,

var = input("enter a number between 1 and 12")
def switch_demo(var):
    switcher = {
                1: "Jan",
                2: "Feb",
                3: "March",
                4: "April",
                5: "May",
                6: "June", 
                7: "July",
                8: "August", 
                9: "Sept",
                10: "Oct",
                11: "Nov",
                12: "Dec"
    }
    print switcher.get(var,"Invalid Month")