在Python中使用字典作为switch语句

2024-04-19 05:28:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用Python编写一个简单的计算器,使用字典。这是我的代码:

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()

但是所有的功能都被激活了。怎么了?


Tags: divadddefaultinputdeflinefloatdict
2条回答

这是因为当字典被填充时,它用操作数执行每个操作, 最后,调用包含Nonedict[op],而不做任何处理。

结果是:

# N.B.: in case this is not clear enough, 
#       what follows is the *BAD* code from the OP
#       with inline explainations why this code is wrong

dict = {
    # executes the function add, outputs the result and assign None to the key '+'
    '+': add(part1, part3), 
    # executes the function sub, outputs the result and assign None to the key '-'
    '-': sub(part1, part3),
    # executes the function mult, outputs the result and assign None to the key '*'
    '*': mult(part1, part3),
    # executes the function div, outputs the result and assign None to the key '/'
    '/': div(part1, part3)
    }

try:
    # gets the value at the key "op" and do nothing with it
    dict[op]
except KeyError:
    default()

这就是为什么您得到所有输出,而在您的try块中什么也没有发生。

你可能真的想:

dict = {
    '+': add,
    '-': sub,
    '*': mult,
    '/': div
    }

try:
    dict[op](part1, part3)
except KeyError:
    default()

但是正如@christian明智地建议的那样,不应该使用python保留名作为变量名,这可能会导致麻烦。我建议您做的另一个改进是只打印一次结果,并使函数lambdas:

d = {
    '+': lambda x,y: x+y,
    '-': lambda x,y: x-y,
    '*': lambda x,y: x*y,
    '/': lambda x,y: x/y
    }

try:
    print(d[op](part1, part3))
except KeyError:
    default()

它将返回结果并打印出来

定义类似字典的形式对str : function

my_dict = {'+' : add, 
           '-' : sub, 
           '*' : mult, 
           '/' : div}

如果要调用操作,请使用my_dict[op]获取函数,然后使用相应的参数传递调用:

 my_dict[op] (part1, part3)
|___________|
      |
  function (parameters)

注意:不要使用Python内置名称作为变量名,否则将隐藏其实现。例如,使用my_dict而不是dict

相关问题 更多 >