在Python中使用字典作为switch语句 [英] Using a dictionary as a switch statement in Python
本文介绍了在Python中使用字典作为switch语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用字典来用Python创建一个简单的计算器.这是我的代码:
I'm trying to make a simple calculator in Python, using a dictionary. Here's my code:
def default():
print "Incorrect input!"
def add(a, b):
print a+b
def sub(a, b):
print a-b
def mult(a, b):
print a*b
def div(a, b):
print a/b
line = raw_input("Input: ")
parts = line.split(" ")
part1 = float(parts[0])
op = parts[1];
part3 = float(parts[2])
dict = {
'+': add(part1, part3),
'-': sub(part1, part3),
'*': mult(part1, part3),
'/': div(part1, part3)
}
try:
dict[op]
except KeyError:
default()
,但所有功能均已激活.有什么问题吗?
but all the functions are activated. What's the problem?
推荐答案
以str : function
形式的对定义字典:
my_dict = {'+' : add,
'-' : sub,
'*' : mult,
'/' : div}
然后,如果要调用操作,请使用my_dict[op]
获取一个函数,然后使用相应的参数传递调用该函数:
And then if you want to call an operation, use my_dict[op]
to get a function, and then pass call it with the corresponding parameters:
my_dict[op] (part1, part3)
|___________|
|
function (parameters)
注意:请勿将Python内置名称用作变量名称,否则您将隐藏其实现.例如,使用my_dict
代替dict
.
Note: Don't use Python built-in names as names of variables, or you will hide its implementation. Use my_dict
instead of dict
for example.
这篇关于在Python中使用字典作为switch语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文