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
我认为它给出了错误,因为我使用的字符串从字典,但不知道如何修复它。
3条答案
按热度按时间8yparm6h1#
calculation_function
被设置为字典的值。这些都是字符串,因此不能像函数一样调用它。相反,应将字典中的值设置为函数,而不是其字符串表示形式。qyswt5oh2#
(1)最好的方法是用函数名替换..即
(2)选项是在
calculation_function
中使用eval
calculation_function = eval(operations[operation_symbol])
im9ewurl3#
尝试python
eval()
方法。关于
eval()
的更多信息:https://www.programiz.com/python-programming/methods/built-in/eval我希望这会有所帮助。