Evening all.
I'm creating a programme which prompts for the rate of return on an investment and calculates how many years it will take to double the investment by using the following formula:
years = 72 / r
Where r is the stated rate of return.
So far my code stops the user from entering zero, but I'm struggling to design a set of loops which will continue to catch non-numeric exceptions if the user insists on doing so. I've therefore resorted to using a series of catch/excepts as shown below:
# *** 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...")
Any advice on designing the necessary loops to capture the exceptions would be great, as well as advice on my coding in general.
Thank you all.