[为什么我应该在字典中使用逗号时却出现语法错误

问题描述 投票:0回答:2

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

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

我在网上搜索过,并尝试了所有方法,但我不知道。

非常感谢您的帮助。

python-3.x dictionary syntax-error comma
2个回答
0
投票

您不能以这种方式使用+,-,* //。他们是操作员。如果您想选择一种操作,快速的方法是在条件下使用

a = input()
b = input()
res = 0

if op == "plus":
  res = a+b
elif op == "minus":
  res = a-b

print(res)

0
投票

[算术运算符+-*/期望两个自变量,但未提供任何自变量。如果要将运算符作为函数传递,请使用operator模块:

import operator as op

operations = {
    "plus": op.add,
    "minus": op.sub,
    "times": op.mul,
    "divided": op.div
}

这是调用操作符功能的方法:

operations["times"](6, 7)
=> 42
© www.soinside.com 2019 - 2024. All rights reserved.