2016-03-01 77 views
0

全部關閉。處理連續異常Python中的異常

我創建一個程序,它提示上的投資回報率,並計算將如何多年採取通過使用下面的公式,投資翻番:

年= 72/R

其中r是規定的回報率。

到目前爲止,我的代碼阻止了用戶輸入零,但我努力設計一組循環,如果用戶堅持這樣做,它將繼續捕獲非數字異常。 我因此訴諸使用一系列捕獲/節選的,如下圖所示:

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

上設計了必要的循環來捕捉異常將是巨大的,以及對我的一般編碼諮詢任何意見。

謝謝大家。

+0

謝謝兩位!我的最終答案張貼如下。 – ChrisToff23

回答

0

我傾向於使用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是必要的。

1

您可能已經做到了這樣,例如(第一什麼來記):

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 

嘗試,只是沒有規定例外的類型不使用。

0

我結束了,這似乎工作,無論多少次,我進入零/非數字如下:

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