首页 > 解决方案 > 异常处理建议

问题描述

我是 Python 新手,正在编写一个小程序来计算贷款欠款。我需要有关程序中异常处理的帮助。

当我输入一个非数字数字时,我让程序重新开始,告诉用户再试一次。虽然当我用数字输入所有内容时,没有计算任何内容并将我带回到程序的开头。我需要一些指导,需要知道我做错了什么。

permonthpayment = 0
loantotal = 0
monthlyinterestrate = 0
numberofpayments = 0 
loanyears = 0

while True:
    loantotal = input("How much money do you need loaned? ")
    loanyears = input("In how many years will full payment be fulfilled? ")
    monthlyinterestrate = input("What's the annual interest rate? (Enter as whole number) ")

try:
    loanyears = float(loanyears)
    loantotal = float(loantotal)
    monthlyinterestrate = float(monthlyinterestrate)
except:
    print("Please enter a valid number and try again.")
    continue

totalpayments = loanyears*12
percent = monthlyinterestrate/100

permonthpayment = (loantotal * (percent/12)) / (1-(1/(1 + (percent/12))) ** (loanyears * 12))
totalpayment = (permonthpayment) * totalpayments

print("You owe $" + str(round(permonthpayment, 2)), "each month")
print("You owe $" +str(round(totalpayment, 2)), "at the end of the pay period")

标签: pythonexception-handling

解决方案


您好,欢迎来到 StackOverflow!您的代码看起来相当不错,只需进行一点小改动就可以让这个东西运行起来。目前,您在循环内要求用户输入,但随后您在验证输入之前while离开了循环。while让我们看一下python中一些正确的输入验证:

while True:
    try:
         loantotal = input("How much money do you need loaned? ")
         loanyears = input("In how many years will full payment be fulfilled? ")
         monthlyinterestrate = input("What's the annual interest rate? (Enter as whole number) ")
    except ValueError:
        print("Sorry, I didn't understand that.")
        #better try again... Return to the start of the loop
        continue
    else:
        # the values were successfully parsed!
        #we're finished with input validation and ready to exit the loop.
        break 
# now we can continue on with the rest of our program
permonthpayment = (loantotal * (percent/12)) / (1-(1/(1 + (percent/12))) ** (loanyears * 12))
totalpayment = (permonthpayment) * totalpayments

print("You owe $" + str(round(permonthpayment, 2)), "each month")
print("You owe $" +str(round(totalpayment, 2)), "at the end of the pay period")

while True:...基本上翻译为...永远,除非您被明确告知停止。所以在我们的例子中,我们将永远要求用户输入,直到他们输入的值不会导致 a ValueError。python 中的ValueError异常是由于无法转换数据类型,或者更具体地说,在我们的例子中是由于无法将原始用户输入转换为浮点数。


推荐阅读