Home > database >  I am trying to make a simple calculator using dictionary
I am trying to make a simple calculator using dictionary

Time:07-31

def add(a,b):
    print (a b)
def sub(a,b):
    print (a-b)
def mult(a,b):
    print (a*b)
def div(a,b):
    print(a/b)



while True:    
    print("1.   \n2. -\n3. * \n4. / \n5. Exit")
    a=int(input("Enter your choice: "))
   
    
    if a==5:
        print("Thank you for using My c@|cu|@t0r")
        break
    else:
        no1=int(input("Enter first no: "))
        no2=int(input("Enter second no: "))
        calc={
                    1:add(no1,no2),
                    2:sub(no1,no2),
                    3:mult(no1,no2),
                    4:div(no1,no2),
                    5:exit()
                }
        calc[a] 
        continue

I have used this code to make a simple calculator, but the output I got is not what I expected. This is the output I am getting :

1.   
2. -
3. * 
4. / 
5. Exit
Enter your choice: 1
Enter first no: 3
Enter second no: 2
5
1
6
1.5

It's running all the functions, where I just want one output

CodePudding user response:

The functions add(a,b) etc. are executed when you construct the dictionary (calc={add(no1,no2), ...), not when you access its element (calc[a]). Because of this, the results of all operations are printed each time.

One option could be to define the dictionary as dictionary of functions (rather than result values), while calling the function of interest after selecting it from the dictionary:

        calc={
                    1:add,
                    2:sub,
                    3:mult,
                    4:div
                }
        calc[a](no1,no2)

Note that you don't need the entry 5:exit(), since that is handled before the else block.

Also, in this case you don't need to define the calc dictionary inside the loop (can be placed before the while).

CodePudding user response:

def add(a,b): return (a b) def sub(a,b): return (a-b) def mult(a,b): return (a*b) def div(a,b): return (a/b)

while True:
print("1. \n2. -\n3. * \n4. / \n5. Exit") a=int(input("Enter your choice: "))

if a==5:
    print("Thank you for using My c@|cu|@t0r")
    break
else:
    no1=int(input("Enter first no: "))
    no2=int(input("Enter second no: "))
    calc={
                1:add(no1,no2),
                2:sub(no1,no2),
                3:mult(no1,no2),
                4:div(no1,no2),
        }
    print(calc[a] )
    continue
  • Related