如何使python代码看起来更干净?

如何使python代码看起来更干净?,python,Python,我试图实践我所学的东西,所以我有了这个想法,它涵盖了我所学的大部分内容。该代码运行良好,但我希望如果有人可以看看,让我知道我可以使它更好 print("available operations (*, +, /, -)\n\"delete\" to delete every previous calculations\n \"exit\" to stop the program ") is_running = True op = &q

我试图实践我所学的东西,所以我有了这个想法,它涵盖了我所学的大部分内容。该代码运行良好,但我希望如果有人可以看看,让我知道我可以使它更好

print("available operations (*, +, /, -)\n\"delete\" to delete every previous calculations\n \"exit\" to stop the program ")

is_running = True
op = ""

while is_running:
    try:
        num1 = float(input(">> "))
    except ValueError:
        print("ValueError")
        continue
    while is_running:
        op = input(">> ")
        if op == "exit":
            is_running = False
            break
        elif op == "delete":
            break

        try:
            num2 = float(input(">> "))
        except ValueError:
            print("ValueError")
            continue

        if op == "*":
            num1 = num1 * num2
            print(num1)
        elif op == "+":
            num1 = num1 + num2
            print(num1)
        elif op == "-":
            num1 = num1 - num2
            print(num1)
        elif op == "/":
            num1 = num1 / num2
            print(num1)
        else:
            print("unavailable operator")
            break

您可以做的一件事是使用字典查找替换运算符的条件,如下代码所述:

import  operator

def calculate(op, num1, num2):
    oper = {
        '+': operator.add,
        '-': operator.sub,
        '*': operator.mul,
        '/': operator.truediv
    }
    try:
        return oper[op](num1, num2)
    except KeyError:
        return 'Invalid Operator'

num1 = 40
num2 = 50
op = '*'
print(calculate(op, num1, num2))

还有一件事,您不需要使用多个try-except语句。对于所有输入,只有一条语句就足够了。在第二个输入语句中也不需要while循环。

这很可能是一个问题,但您可以用字典查找替换运算符条件。噢,谢谢,这看起来好多了。我不知道操作员模块