简体   繁体   中英

Handling continuos Exceptions in Python

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.

You may have done it like this, for example (first what came to mind):

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

Try not to use except without specifying type of exception.

I tend to use a while loop.

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: ")

Since what you're checking is not easily expressed as a conditional (see Checking if a string can be converted to float in Python ), the while True and break are necessary.

I ended up with the following which seems to work no matter how many times I entered zero/non-numeric:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM