简体   繁体   English

我如何正确地将 try-except 实施到这个程序中?

[英]How do I proper implement try-except into this program?

I am taking an introduction to Python course and I cannot figure out how to add some try-except code to catch exceptions like zerodivisionerror and keyboardinterrupt.我正在介绍 Python 课程,但我不知道如何添加一些 try-except 代码来捕获诸如 zerodivisionerror 和 keyboardinterrupt 之类的异常。 Full code below:完整代码如下:

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()

the print statements are not the place where exceptions happen.打印语句不是发生异常的地方。 ZeroDivisionError happens in ZeroDivisionError 发生在

div = float(num_1) / float(num_2)

KeyboardInterrupt can happen any time after app started. KeyboardInterrupt 可以在应用程序启动后的任何时间发生。

so try-except KeyboardInterrupt for the whole while block.所以在整个while块中尝试-除了KeyboardInterrupt。

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

and try-except ZeroDivisionError for the division statement.和 try-except ZeroDivisionError 用于除法语句。

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

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

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