我试图使用dictionary在Python中实现switch
语句,但我遇到了一个问题。你知道吗
下面是我正在尝试的:
print "Enter value of i"
i=eval(raw_input())
j=0
def switch(i):
print "Hello\n"
return {True: 'gauw',
i==1: a(10),
i==2: a(20),
}[True]
def a(t):
global j
j=t
switch(i)
print j
输出:
输入i的值
1个
20个
但我预计10岁输出。所以呢,这里的主要问题是,它正在为i==1
&;i==2
执行这两个语句。另外,我不能在这里使用break
。你知道吗
那么如何获得期望的输出呢?你知道吗
我想你的开关应该是:
在构建字典时,a(10)和a(20)都被调用
编辑添加默认案例,因为有人关心这个问题。你知道吗
我把行动和逻辑分开,像这样:
你把自己搞复杂了吗?如果只是switch的实现,则使用If和elif。你知道吗
会成功的
相关问题 更多 >
编程相关推荐