-1

I am trying to implement a calculator operation using dictionary, instead of if-else conditions. However instead of running only the one required function, all the functions defined in the dictionary is run. Following is the code:\n

def add(a,b):
    print(f'Sum of {a} and {b} is:',(a+b))
def diff(a,b):
    print(f'Difference of {a} and {b} is:',(a-b))
def prod(a,b):
    print(f'Product of {a} and {b} is:',(a*b))
n1 = 5
n2 = 3
op = int(input("Enter the command for operation (1-3): "))
dic = {1: add(n1,n2), 2: diff(n1,n2), 3: prod(n1,n2)}
dic[op]

If i am entering 3 the expected output is 15 as only the value prod(n1,n2) should be triggered for the key 3. However i am getting the result of all the three functions as output no matter what my input is (in the range of 1-3). Why is it happening and how can i ensure that only one function is called, as per my input ?

Junaid Ahmad
  • 41
  • 1
  • 9
  • 2
    You are calling the functions when you define the dictionary. `add(n1,n2)` calls the function which then prints the values. – Mark Apr 25 '21 at 21:04

2 Answers2

3

Try {"a" : print("a"), "b" : print("b")}. As you can see it still prints a and b, even if you do not call it. This is due to the items being evaluated.

Instead of putting the results of the functions into the dict (the results are all None, as you do not return anything from your functions) you could put the functions themselves:

def add(a,b):
    print(f'Sum of {a} and {b} is:',(a+b))
def diff(a,b):
    print(f'Difference of {a} and {b} is:',(a-b))
def prod(a,b):
    print(f'Product of {a} and {b} is:',(a*b))
n1 = 5
n2 = 3
op = int(input("Enter the command for operation (1-3): "))
dic = {1: add, 2: diff, 3: prod}
dic[op](n1, n2)

This code takes the function at the specified index and calls it with n1 and n2 as arguments.

Jan
  • 42,290
  • 8
  • 54
  • 79
DownloadPizza
  • 3,307
  • 1
  • 12
  • 27
0
def add(a,b):
    return (f'Sum of {a} and {b} is:',(a+b))
def diff(a,b):
    return (f'Difference of {a} and {b} is:',(a-b)) 
def prod(a,b):
    return(f'Product of {a} and {b} is:',(a*b))
n1 = 5
n2 = 3
op = int(input("Enter the command for operation (1-3): "))
dic = {1: add(n1,n2), 2: diff(n1,n2), 3: prod(n1,n2)}
print(dic[op])

your program is printing all the values because you are calling every function inside dic and in each fuction you are printing. rather than that you shoud return and then print that element which you need using key which in your case is 'op'