简体   繁体   English

输入循环 - Python 中的字典查找和递归计算器

[英]Input Loop - Dictionary Lookup and Recursion Calculator in Python

brand new at Python, and been experimenting with various calculator code methods in Python.全新 Python,并在 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.请注意,事实上,代码非常脆弱,因为任何不能重新转换为数字运算符数字模式(或“C”)的东西都需要处理。 You could use pattern matching to check if the operation is valid before passing to eval first, and manage bad cases as you wish.您可以在首先传递给eval之前使用模式匹配来检查操作是否有效,并根据需要管理不良情况。

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.向代码添加更多验证会很好......比如确保只存在一个运算符,并且在 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.它比使用 python 使用的 '**' 更容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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