Home > other >  Input Loop - Dictionary Lookup and Recursion Calculator in Python
Input Loop - Dictionary Lookup and Recursion Calculator in Python

Time:01-17

brand new at Python, and been experimenting with various calculator code methods in Python.

I found the following code:

from operator import pow, truediv, mul, add, sub  

operators = {
  ' ': add,
  '-': sub,
  '*': mul,
  '/': truediv
}

def calculate(s):
    if s.isdigit():
        return float(s)
    for c in operators.keys():
        left, operator, right = s.partition(c)
        if operator in operators:
            return operators[operator](calculate(left), calculate(right))

calc = input("Type calculation:\n")
print("Answer: "   str(eval(calc)))

and I'm just wondering how one would formulate an input loop for this one.

CodePudding user response:

from operator import pow, truediv, mul, add, sub  

operators = {
  ' ': add,
  '-': sub,
  '*': mul,
  '/': truediv
}

def calculate(s):
    if s.isdigit():
        return float(s)
    for c in operators.keys():
        left, operator, right = s.partition(c)
        if operator in operators:
            return operators[operator](calculate(left), calculate(right))
cont = 'y'
while cont.lower() == 'y':
    calc = input("Type calculation:\n")        
    print("Answer: "   str(eval(calc)))
    cont = input("Do you want to continue? (y/n)")

It would be good to add more validations to the code... like ensuring that only one operator exists and that there are numbers on either side of the operator inside the calc function.

Also, you are importing power but don't have a symbol for it. Can use '^' if you haven't already? It is easier than using '**' which python uses.

CodePudding user response:

The script will ask you continuosly for operation to compute as follows:

while True:
    calc = input("Type calculation (C to exit):\n")
    if calc.upper().strip() == "C":
        break
    print("Answer: "   str(eval(calc)))

Note that, as it is, the code is extremely fragile, given that anything which cannot be reconducted to a number operator number pattern (or "C"), will need to be treated. You could use pattern matching to check if the operation is valid before passing to eval first, and manage bad cases as you wish.

  •  Tags:  
  • Related