python TypeError:“str”对象不可调用,无法调用函数

1tuwyuhd  于 2023-01-29  发布在  Python
关注(0)|答案(3)|浏览(229)
def add(n1, n2):
  return n1 + n2

def subtract(n1, n2):
  return n1 - n2

def multiply(n1, n2):
  return n1 * n2

def divide(n1, n2):
  return n1 / n2

operations = {
  "+": "add",
  "-": "subtract",
  "*": "multiply",
  "/": "divide"
}

num1 = int(input("What's the first number?: "))
num2 = int(input("What's the second number?: "))

for operation in operations:
  print(operation)

operation_symbol = input("Pick an operation from the line above: ")

calculation_function = operations[operation_symbol]
answer = calculation_function(num1, num2)

print(f"{num1} {operation_symbol} {num2} = {answer}")

它给出了以下错误:

Traceback (most recent call last):
  File "main.py", line 34, in <module>
    answer = calculation_function(num1, num2)
TypeError: 'str' object is not callable

我认为它给出了错误,因为我使用的字符串从字典,但不知道如何修复它。

8yparm6h

8yparm6h1#

calculation_function被设置为字典的值。这些都是字符串,因此不能像函数一样调用它。相反,应将字典中的值设置为函数,而不是其字符串表示形式。

operations = {
  "+": add,
  "-": subtract,
  "*": multiply,
  "/": divide
}
qyswt5oh

qyswt5oh2#

(1)最好的方法是用函数名替换..即

operations = {
  "+": add,
  "-": subtract,
  "*": multiply,
  "/": divide
}
    • 或**

(2)选项是在calculation_function中使用eval
calculation_function = eval(operations[operation_symbol])

im9ewurl

im9ewurl3#

尝试python eval()方法。

...
operation_symbol = input("Pick an operation from the line above: ")
calculation_function = operations[operation_symbol]

try:
    answer = eval(f'{calculation_function}({num1}, {num2})')
except KeyError:
    raise ValueError('invalid input')

print(f"{num1} {operation_symbol} {num2} = {answer}")

关于eval()的更多信息:https://www.programiz.com/python-programming/methods/built-in/eval
我希望这会有所帮助。

相关问题