为什么在字典中使用逗号时会出现语法错误,即使我应该使用它们



我正在用python编写我的第一个程序,我试图为计算器中的操作做一个字典,但IDLE说+号后的第一个逗号中存在语法错误。 我已经在文档中搜索了正确的语法,它说我必须使用逗号。 但它们不起作用

operations = {"plus":+,
"minus":-,
"times":*,
"divided":/
}

我在网上搜索过,并尝试了所有方法,但我无法弄清楚。

你不能这样使用 +,-,*,/。他们是运营商。如果要选择操作,快速方法是使用if条件

a = input()
b = input()
res = 0
if op == "plus":
res = a+b
elif op == "minus":
res = a-b
print(res)

虽然其他人已经提供了几种不同的方法,但我只是为了多样化而扔进去,但我还没有测试它的效率。它使用 lambda 作为匿名函数来返回值

operations = {"plus":lambda a,b: a+b,
"minus":lambda a,b: a-b,
"times":lambda a,b: a*b,
"divided":lambda a,b: a/b
}
print(operations["plus"](10,15))
print(operations["minus"](50,15))
print(operations["times"](10,5))
print(operations["divided"](100,20))

输出

25
35
50
5.0

最新更新