异常处理建议

时间:2018-08-31 03:30:33

标签: python exception-handling

我是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")

1 个答案:

答案 0 :(得分:0)

您好,欢迎来到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:...本质上意味着永远做...除非明确告诉您停止。因此,在本例中,我们将永远要求用户输入,直到他们输入不会导致ValueError的值为止。 python中的ValueError异常是由于无法转换数据类型引起的,或更具体地,在我们的情况下是由于未能将原始用户输入转换为浮点数引起的。