【问题标题】:Handling continuos Exceptions in Python在 Python 中处理连续异常
【发布时间】:2016-03-01 20:50:12
【问题描述】:

晚上好。

我正在创建一个程序,它会提示投资回报率,并使用以下公式计算将投资翻倍需要多少年:

年 = 72 / r

其中 r 是规定的回报率。

到目前为止,我的代码阻止用户输入零,但我正在努力设计一组循环,如果用户坚持这样做,它将继续捕获非数字异常。 因此,我使用了一系列 catch/excepts,如下所示:

# *** METHOD ***
def calc(x):
    try:
        #So long as user attempts are convertible to floats, loop will carry on.
        if x < 1:
            while(x < 1):
                x = float(input("Invalid input, try again: "))
        years = 72/x
        print("Your investment will double in " + str(years) + "  years.")
    except:
        #If user inputs a non-numeric, except clause kicks in just the once and programme ends.
        print("Bad input.")

# *** USER INPUT ***
try:
    r = float(input("What is your rate of return?: "))
    calc(r)
except:
    try:
        r = float(input("Don't input a letter! Try again: "))
        calc(r)
    except:
        try:
            r = float(input("You've done it again! Last chance: "))
            calc(r)
        except:
            print("I'm going now...")

任何关于设计必要循环以捕获异常的建议以及关于我的一般编码的建议都会很棒。

谢谢大家。

【问题讨论】:

  • 谢谢你们!我的最终答案发布在下面。

标签: python loops exception-handling


【解决方案1】:

例如,您可能已经这样做了(首先想到的):

while True:
    try:
        r = float(input("What is your rate of return?: "))
    except ValueError:
        print("Don't input a letter! Try again")
    else:
        calc(r)
        break

在没有指定异常类型的情况下尽量不要使用except。

【讨论】:

    【解决方案2】:

    我倾向于使用while 循环。

    r = input("Rate of return, please: ")
    while True:
      try:
        r = float(r)
        break
      except:
        print("ERROR: please input a float, not " + r + "!")
        r = input("Rate of return, please: ")
    

    由于您要检查的内容不容易表示为条件(请参阅Checking if a string can be converted to float in Python),因此while Truebreak 是必要的。

    【讨论】:

      【解决方案3】:

      无论我输入多少次零/非数字,我都得到了以下结果:

      # *** METHOD ***
      def calc(x):
          years = 72/x
          print("Your investment will double in " + str(years) + " years.")
      
      # *** USER INPUT ***
      while True:
        try:
          r = float(input("What is your rate of return?: "))
          if r < 1:
              while r < 1:
                  r = float(input("Rate can't be less than 1! What is your rate of return?: "))
          break
        except:
          print("ERROR: please input a number!")
      
      calc(r)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-16
        • 1970-01-01
        • 2017-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多