Home > Blockchain >  TypeError: 'str' object is not callable, Can't call function
TypeError: 'str' object is not callable, Can't call function

Time:01-28

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.

CodePudding user response:

This error is occurring because you are trying to call the functions stored in the operations dictionary as strings, rather than as actual function references.

One way to fix this is to use the eval() function, which can be used to convert a string into a function call. However, using eval() is generally not recommended due to security concerns.

A better way to fix this would be to change the values in the operations dictionary to be actual references to the functions, rather than strings. You can do this by removing the quotes around the function names:

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

By doing this, you are storing the actual function in the dictionary and not a string. Then when you call calculation_function(num1, num2) you are calling the actual function and not a string.

Alternatively you can use a 'if-elif' statement block to check for the operation symbol and call the function according to it.

if operation_symbol == " ":
    answer = add(num1,num2)
elif operation_symbol == "-":
    answer = subtract(num1,num2)

And so on..

By doing this you are directly calling the function and not trying to call a string.

CodePudding user response:

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
}

CodePudding user response:

(1) The best method is to replace with name of function.. i.e

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

OR

(2) Option is to use eval in calculation_function

calculation_function = eval(operations[operation_symbol])

CodePudding user response:

try python eval() method.

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

More about eval(): https://www.programiz.com/python-programming/methods/built-in/eval

I hope this will help.

  • Related