【发布时间】: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