异常处理Advi

2024-10-03 17:24:12 发布

您现在位置:Python中文网/ 问答频道 /正文

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

当我输入一个非数字的数字时,我会让程序从头开始重新启动,告诉用户再试一次。虽然当我用数字输入all时,没有任何东西被计算出来,并把我带回到程序的开头。我需要一些指导,需要知道我做错了什么

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

Tags: the程序numberinput数字floatprintpercent
1条回答
网友
1楼 · 发布于 2024-10-03 17:24:12

大家好,欢迎来到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:...本质上翻译为do。。。除非你被明确告知停止。所以在我们的例子中,我们将永远要求用户输入,直到他们输入的值不会导致ValueError。python中的ValueError异常是由于未能强制转换数据类型,或者更具体地说是由于未能将原始用户输入转换为float

相关问题 更多 >