【问题标题】:How do I proper implement try-except into this program?如何在该程序中正确实施 try-except ?
【发布时间】:2019-11-28 01:31:03
【问题描述】:

我正在学习 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()

【问题讨论】:

  • 希望这不是大学课程。如果他们有一个检查抄袭的系统,在这里发布你的代码可能会在提交时被标记。阅读文档手册。
  • 是的。废话我什至没有考虑过。我迫切需要帮助。那好吧。现在太晚了。

标签: python try-except


【解决方案1】:

打印语句不是发生异常的地方。 ZeroDivisionError 发生在

div = float(num_1) / float(num_2)

键盘中断可能在应用启动后的任何时间发生。

所以在整个 while 块中尝试将 KeyboardInterrupt 除外。

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

除法语句的尝试除 ZeroDivisionError。

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

【讨论】:

  • 谢谢。这需要一些额外的工作,但你肯定让我走上了正确的轨道。我的思考过程有点偏离,但就像我说的那样。你帮我弄清楚如何让它发挥作用。谢谢
猜你喜欢
  • 2012-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-20
  • 1970-01-01
  • 1970-01-01
  • 2022-12-22
相关资源
最近更新 更多