在Python中处理continuos异常

2024-05-23 18:10:40 发布

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

晚上好

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

年=72/r

其中r是规定的回报率

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

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

任何关于设计必要的循环以捕获异常的建议,以及关于我的总体编码的建议都是非常好的

谢谢大家


Tags: 用户in程序inputcalcfloatwill建议
3条回答

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

不管我输入了多少次零/非数字,我最终得到了以下结果:

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

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

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

相关问题 更多 >