小编use*_*163的帖子

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

我正在尝试使用字典在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)

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

python dictionary

17
推荐指数
2
解决办法
2万
查看次数

标签 统计

dictionary ×1

python ×1