how to implement the switch case in python..?
This question already has an answer here:
Fixing your Bugs
You need to add a comma at the end of each item:
1: "Jan",
2: "Feb",
Working program:
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))
Simpler Solution
You should have a look at the calendar
module. It already provides all months names:
>>> import calendar
>>> calendar.month_name[3]
'March'
Switch case is a very powerful control tool in programming as we can control to execute different blocks of code with it. In python you can implement it by using dictionary method and for your code posted,
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")
链接地址: http://www.djcxy.com/p/42760.html上一篇: 将Python切换重写为更紧凑的方式