处理Python中的例外异常

时间:2016-03-01 20:50:13

标签: python loops exception-handling

晚上。

我创建的程序会提示投资回报率,并计算使用以下公式将投资加倍所需的年数:

年= 72 / r

其中r是规定的回报率。

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

# *** 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...")

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

谢谢大家。

3 个答案:

答案 0 :(得分: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

尽量不要使用,除非没有指定例外类型。

答案 1 :(得分:0)

我倾向于使用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是必需的。

答案 2 :(得分:0)

我最终得到以下内容,无论我输入零/非数字的次数,这似乎都有效:

# *** 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)