晚上好
我正在创建一个程序,它会提示一项投资的回报率,并使用以下公式计算需要多少年才能使投资翻一番:
年=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...")
任何关于设计必要的循环以捕获异常的建议,以及关于我的总体编码的建议都是非常好的
谢谢大家
我倾向于使用
while
循环由于您要检查的内容不容易表示为条件(请参见Checking if a string can be converted to float in Python),因此
while True
和break
是必需的不管我输入了多少次零/非数字,我最终得到了以下结果:
例如,您可能是这样做的(首先想到的是):
在不指定异常类型的情况下,尽量不要使用except
相关问题 更多 >
编程相关推荐