在 Python 中使用 try/except 和 while 循环进行计算器

using try/except & while loop for calculator in python

提问人:Youzohka 提问时间:5/2/2023 最后编辑:M ZYouzohka 更新时间:5/2/2023 访问量:353

问:

我正在尝试创建一个计算器并使用防御性编程来避免意外事件和用户输入。

我包括一个用于用户输入的 / 块和零除法。tryexcept

当我输入除法运算符来计算零除法时,我的循环并没有带我回去输入数字。它带我回去输入运算符。

我也努力重新循环计算器,以便用户开始新的计算。

非常感谢您的帮助。

while True:

    try:
        
        num1 = float(input("Please enter a number:"))
        num2 = float(input("Please enter another number: "))
        break
        
    except ValueError:
        print("Wrong key entered. Please key in a number")

operator = input("Please enter the operator (+, -, *, /): ")        
while True: 
        
    if operator == "+":
        calculation = num1 + num2
        entry = ("{} + {} = {}".format(num1,num2,calculation))  
        print(entry) 
        
    elif operator == "-":
        calculation = num1 - num2
        entry = ("{} - {} = {}".format(num1,num2,calculation)) 
        print(entry)
        
    elif operator == "*":
        calculation = num1 * num2
        entry = ("{} * {} = {}".format(num1,num2, calculation)) 
        print(entry)   
        
    elif operator == "/":
        try:    
            calculation = num1 / num2
            entry = ("{} / {} = {}".format(num1, num2, calculation))
            print(entry)
            break
            
        except ZeroDivisionError:
            print("You cannot divide by zero. Please try again!") 
    
    choice = input("Continue - Y / No - N: ")
    if choice == "N":
            break
    else:   
        print("You have not entered a valid operator, please try again.")
python while循环 计算器 try-except 防御性编程

评论

0赞 Michael Butscher 5/2/2023
您需要对整个代码进行一个大循环才能返回到代码的开头(操作数的输入),并且您可以从循环中的任何位置返回到开头。continue

答:

0赞 Barmar 5/2/2023 #1

将计算代码放在第一个循环中,而不是单独的循环中。然后,当出现算术错误或用户说继续时,您可以返回到数字提示。while True:

while True:
    try:
        num1 = float(input("Please enter a number:"))
        num2 = float(input("Please enter another number: "))

        operator = input("Please enter the operator (+, -, *, /): ")        

        if operator == "+":
            calculation = num1 + num2
            entry = ("{} + {} = {}".format(num1,num2,calculation))  
            print(entry) 

        elif operator == "-":
            calculation = num1 - num2
            entry = ("{} - {} = {}".format(num1,num2,calculation)) 
            print(entry)

        elif operator == "*":
            calculation = num1 * num2
            entry = ("{} * {} = {}".format(num1,num2, calculation)) 
            print(entry)   

        elif operator == "/":
            calculation = num1 / num2
            entry = ("{} / {} = {}".format(num1, num2, calculation))
            print(entry)

        else:   
            print("You have not entered a valid operator, please try again.")
            continue

        choice = input("Continue - Y / No - N: ")
        if choice == "N":
            break

    except ValueError:
        print("Wrong key entered. Please key in a number")

    except ZeroDivisionError:
        print("You cannot divide by zero. Please try again!") 
0赞 KSs 5/2/2023 #2

如果你想循环整个计算器并能够控制整个过程,你可以将操作移动到方法中,并将它们添加到一个while循环中

def choose_numbers():
    try:
        num1 = float(input("Please enter a number:"))
        num2 = float(input("Please enter another number: "))
        return {"num1":num1,"num2":num2}
    except ValueError:
        print("Wrong key entered. Please key in a number")

def choose_operator(num1, num2):

    operator = input("Please enter the operator (+, -, *, /): ")

    if operator == "+":
        calculation = num1 + num2
        entry = ("{} + {} = {}".format(num1,num2,calculation))
        print(entry)

    elif operator == "-":
        calculation = num1 - num2
        entry = ("{} - {} = {}".format(num1,num2,calculation))
        print(entry)

    elif operator == "*":
        calculation = num1 * num2
        entry = ("{} * {} = {}".format(num1,num2, calculation))
        print(entry)

    elif operator == "/":
        calculation = num1 / num2
        entry = ("{} / {} = {}".format(num1, num2, calculation))
        print(entry)




if __name__ == '__main__':
    while True:
        number = choose_numbers()
        try:
            choose_operator(number["num1"], number["num2"])
        except ZeroDivisionError:
            print("You cannot divide by zero. Please try again!")
0赞 Rui Vieira 5/2/2023 #3

我想说的是,你缺少一个外部的while来维持循环,直到程序达到选择的答案N。

此外,您可以使用函数隔离代码中的任务,使其更易于理解和维护。类似的东西,在主流中:

while True
    get_numbers()
    get_operation()
    do_calculation()
    get_choice()

在 get_numbers() 处,接受带有 first while 循环的数字以进行验证。

在 get_operation() 接受操作。我建议实现类似的while来验证允许的操作。

在 do_calculation() 中,仅保留 if/elif 结构,并尝试防止除以零错误(虽然这里不适用)

在 get_choice() 中,接受继续进行更多计算或退出的决定,但请记住验证两个选项 Y 或 N,并可能将输入转换为上限。同样,欢迎使用一段时间来保证用户输入有效的选择。