如何在该程序中正确实现tryexcept?

2024-03-29 10:28:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习Python入门课程,我不知道如何添加一些try-except代码来捕获诸如zerodivisionerror和keyboardinterrupt之类的异常。完整代码如下:

def math():
    x = float(0)
    Flag = True
    while(Flag):

        low_rng = input("Select your Lower range :")
        hi_rng = input("Select your Higher range :")
        num_1 = input("Enter your first number :")
        num_2 = input("Enter your second number :")
        add = float(num_1) + float(num_2)
        sub = float(num_1) - float(num_2)
        mult = float(num_1) * float(num_2)
        div = float(num_1) / float(num_2)



        def IsInRange():

            if float(num_1) < float(low_rng) or float(num_2) > float(hi_rng):
                print("The input values are out side the input ranges.") 
                print("Please check the numbers and try again.")
                print("Thanks for using our calculator.")
                IsInRange = False

            else:
                try:
                    print("The result of " + num_1 + " + "  + num_2 + " is " + str(add))
                    print("The result of " + num_1 + " - "  + num_2 + " is " + str(sub))
                    print("The result of " + num_1 + " * "  + num_2 + " is " + str(mult))
                    print("The result of " + num_1 + " / "  + num_2 + " is " + str(div))
                    IsInRange = True
                except ZeroDivisionError:
                    print("You can not divide by zero!")
                except KeyboardInterrupt:
                    print("User Interruption!")


        IsInRange()
        cont = input('Continue Looping y/n ')
        if(cont=="n"):
            print ("Ending loop")
            print("Done")
            Flag = False
        continue
math()

Tags: oftheinputyourisresultfloatnum
1条回答
网友
1楼 · 发布于 2024-03-29 10:28:56

print语句不是发生异常的地方。 零错误发生在

div = float(num_1) / float(num_2)

键盘中断可以在应用程序启动后的任何时间发生

所以,在整个while块中尝试除键盘中断之外的其他操作

try 
    while(Flag):
        ....
except KeyboardInterrupt
    ...

并尝试对除法语句执行除零除法错误

try 
    div = float(num_1) / float(num_2)
except ZeroDivisionError 
    ...

相关问题 更多 >