全部關閉。處理連續異常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...")
上設計了必要的循環來捕捉異常將是巨大的,以及對我的一般編碼諮詢任何意見。
謝謝大家。
謝謝兩位!我的最終答案張貼如下。 – ChrisToff23