【发布时间】:2015-03-06 06:33:46
【问题描述】:
在遵循一些代码之后,我试图使用dictionary 在Python 中实现C 之类的switch-case。我有以下代码。
case = {'1': "case_1", '2': "case_2"}
def case_1():
print "case 1"
def case_2():
print "case 2"
x = raw_input("Enter 1 or 2 :")
if x == '1' or x == '2':
print case[x]
case_1()
case[x]()
else:
print "Please enter 1 or 2 only"
我得到如下输出和错误。
Enter 1 or 2 :1
case_1
case 1
Traceback (most recent call last):
File "test.py", line 17, in <module>
case[x]()
TypeError: 'str' object is not callable
谁能告诉我这里出了什么问题?
【问题讨论】:
标签: python python-2.7 dictionary switch-statement