1
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}")

It's giving the following error:

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

I think it's giving the error because I am using string from the dictionary but don't really know how to fix it.

oz cem
  • 11
  • 2
  • 1
    Use the name of the function instead of the string: `{'+': add, '-': subtract, '*': multiply, '/': divide}`. In addition, there are already defined operator functions (`add`, `sub`, `mul`, `truediv`) in `operator`. – Mechanic Pig Jan 28 '23 at 04:40

1 Answers1

0

calculation_function is being set to the value of your dictionary. These are all strings, thus it cannot be called like a function. Instead you should set the values in your dict to be the functions, not their string representations.

operations = {
  "+": add,
  "-": subtract,
  "*": multiply,
  "/": divide
}
BTables
  • 4,413
  • 2
  • 11
  • 30