how to implement the switch case in python..?
本问题已经有最佳答案,请猛点这里访问。
请检查以下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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行遇到语法错误如何解决错误?
修正你的错误
您需要在每个项目的末尾添加一个逗号:
1 2 | 1:"Jan", 2:"Feb", |
工作程序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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)) |
更简单的解决方案
您应该看看
1 2 3 | >>> import calendar >>> calendar.month_name[3] 'March' |
switch case是编程中非常强大的控制工具,因为我们可以用它控制执行不同的代码块。在python中,您可以使用dictionary方法实现它,对于您发布的代码,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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") |