Asif Rot
Asif Rot

Reputation: 17

Beginner - TypeError: 'dict' object is not callable

I'm trying to build a calculator using 'lambda' as the options for operators. The problem is - I can not find a way to print it so that I will get an answer using 2 numbers that the user selects and one of the operators in the list when all this is equal to what the user chose.

I know I can use 'if' & 'elif' for each operator individually to solve this problem but I deliberately want to use 'lambda'. I do this to learn how to use this function in this way and also to allow me or anyone who wants to use it in the future to add operators more easily and quickly.

def InputNumber(message):
    while True:
        try:
            userinput = int(input(message))
        except ValueError:
            print("Not an integer! Please try again.")
        else:
            return userinput


operators = {
    "+": lambda n: num1 + num2,
    "*": lambda n: num1 * num2,
    "-": lambda n: num1 - num2,
    "/": lambda n: num1 / num2,
}


def cal_fund(message):
    while True:
        operator = (input("Please enter your operation (+, -, *, /): "))
        if operator in list(operators.keys()):
            return operator
        else:
            print("Not an operation! Please try again.")


while True:
    num1 = InputNumber("Please enter a number: ")
    opera = cal_fund("Please enter your operation (+, -, *, /): ")
    num2 = InputNumber("Please enter another number: ")

    print(operators(num1, num2))
    print("-" * 15)

for now, this is the error I get (I know that the problem is that I use dictionary but I didn't find anything else to use for this particular way):

Traceback (most recent call last):
File "", line 34, in <module>
  print(operators(num1, num2))
TypeError: 'dict' object is not callable

Upvotes: 0

Views: 238

Answers (1)

Austin
Austin

Reputation: 26039

Problems:

  • operators is a dictionary that cannot be called. So, operators(..) is not allowed.

  • lambda in your dictionary values should receive two values for the operation to work.

Fix:

Update your dictionary as:

operators = {
    "+": lambda num1, num2: num1 + num2,
    "*": lambda num1, num2: num1 * num2,
    "-": lambda num1, num2: num1 - num2,
    "/": lambda num1, num2: num1 / num2,
}

And then use:

print(operators[opera](num1, num2))

Upvotes: 5

Related Questions