1

Following a udemy course and I'm stuck at this " 'str object is not callable " error. I've basically copied and pasted the snippet of code giving me an issue and it still produces the same error. Haven't found anything with the exact issue I'm having but I won't be surprised if it's a comically simple fix!

The issue is with the "ops_function" bit throwing a 'str' object is not callable error.

Let me know if you need more info and thank you for any insight!

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}")
wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • 5
    use `add` instead of `"add"` inside `operations` – wjandrea Sep 22 '21 at 21:21
  • 1
    BTW, welcome to Stack Overflow! Check out the [tour], and [ask] if you want tips. – wjandrea Sep 22 '21 at 21:22
  • 1
    Functions in python are [first class](https://stackoverflow.com/questions/27392402/what-is-first-class-function-in-python), meaning they can be referenced directly, like a variable. Putting their name in quotes just creates a string with the same contents as the function name, but Python wouldn't automatically know to translate the string's contents to a function name and then retrieve the actual function. There are ways to execute text as code but that's not necessary here. – Random Davis Sep 22 '21 at 21:25
  • 2
    For debugging help in the future, please make a [mre] including the full error message and minimized code. – wjandrea Sep 22 '21 at 21:26

1 Answers1

5

Your operations dictionary maps strings to strings. You want it to map strings to functions. For example, "add" is a string, while add is a function. In effect, you're trying to do "add"(first, second), when what you want is add(first, second). So change operations to:

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

I.e. remove the quotes from the function names. That way they'll be functions rather than strings.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41