如何纠正不可调用的 str?

1 python

在学习 udemy 课程后,我陷入了“'str object is not callable”错误。我基本上已经复制并粘贴了给我带来问题的代码片段,但它仍然产生相同的错误。还没有发现任何与我遇到的确切问题相关的内容,但如果这是一个简单得可笑的修复,我不会感到惊讶!

问题在于“ops_function”位抛出“str”对象不可调用错误。

如果您需要更多信息,请告诉我,感谢您的见解!

from art import logo
print(logo)

def add(a, b):
    return a + b
def subtract(a, b):
    return a - b
def multiply(a, b):
    return a * b
def divide(a, b):
    return a / b

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

first = int(input("Enter a number: "))
second = int(input("Enter another number: "))

for op in operations:
    print(op)

op_choice = input("Select an operator from the list above: ")
ops_function = operations[op_choice]
answer = ops_function(first, second)

print(f"{first} {op_choice} {second} = {answer}")
Run Code Online (Sandbox Code Playgroud)

Tom*_*zes 5

您的operations字典将字符串映射到字符串。您希望它将字符串映射到函数。例如,"add"是字符串,而add是函数。实际上,"add"(first, second)当你想要做的时候,你正在尝试做add(first, second)。所以改为operations

operations = {
    "+": add,
    "-": subtract,
    "*": multiply,
    "/": divide
}
Run Code Online (Sandbox Code Playgroud)

即删除函数名称中的引号。这样它们将是函数而不是字符串。