简体   繁体   中英

Input Loop - Dictionary Lookup and Recursion Calculator in Python

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM