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

use*_*163 17 python dictionary

我正在尝试使用字典在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()
Run Code Online (Sandbox Code Playgroud)

但所有功能都被激活了.有什么问题?

Chr*_*ian 15

像对形式一样定义字典str : function:

my_dict = {'+' : add, 
           '-' : sub, 
           '*' : mult, 
           '/' : div}
Run Code Online (Sandbox Code Playgroud)

然后如果你想调用一个操作,my_dict[op]用来获取一个函数,然后用相应的参数传递它:

 my_dict[op] (part1, part3)
|___________|
      |
  function (parameters)
Run Code Online (Sandbox Code Playgroud)

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


zmo*_*zmo 12

这是因为当填充字典时,它会使用操作数执行每个操作,最后,您将调用dict[op]包含None它并且不执行任何操作的操作.

会发生什么:

# 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()
Run Code Online (Sandbox Code Playgroud)

这就是为什么你得到所有输出,你的try块没有任何事情发生.

你可能想要真正做到:

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

try:
    dict[op](part1, part3)
except KeyError:
    default()
Run Code Online (Sandbox Code Playgroud)

但正如@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()
Run Code Online (Sandbox Code Playgroud)

这将返回结果并打印出来