1

This is my code.

n1, n2 = (int(input("Enter number: ")) for _ in range(2))
print("Select Your Choice: ")
print(" 1: Addition",
       "2: Substraction",
       "3: Multiplication",
       "4: Division")
choice = int(input())

switcher = {
        1: "Addition",
        2: "Substraction",
        3: "Multiplication",
        4: "Division",
    }
def addition(n1,n2):
    n1 += n2
    return n1

def substraction(n1,n2):
    n1 -= n2
    return n1

def multiplication(n1,n2):
    n1 *= n2
    return n1

def division(n1,n2):
    n1 /= n2
    return n1

def calculator(choice,n1,n2):
    return switcher.get(choice,"Invalid")(n1,n2)

print(calculator(choice,n1,n2))

I got below error.

> Traceback (most recent call last):   
> simple calculator with dictionary.py", line 36, in <module>
> print(calculator(choice,n1,n2))   
> simple calculator with dictionary.py", line 34, in calculator

> > return switcher.get(choice,"Invalid")(n1,n2) 
> TypeError: 'str' object is not callable

Can anyone solve this error?

2
  • 2
    Please reformat the code, its hardly readable. Commented May 29, 2020 at 5:04
  • Could you make it work? Commented May 29, 2020 at 7:16

1 Answer 1

3

The values in switcher have to be the functions you defined, not strings.

switcher = {
    1: addition,
    2: substraction,
    3: multiplication,
    4: division,
}

Put this initialization of switcher after the definition of your functions.

You'll still get the "string not callable" error for invalid inputs, because

"Invalid"(n1, n2)

is not a valid function call. Adjust calculator to do something else for invalid inputs.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.