python - 异常处理建议
问题描述
我是 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")
解决方案
您好,欢迎来到 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
异常是由于无法转换数据类型,或者更具体地说,在我们的例子中是由于无法将原始用户输入转换为浮点数。
推荐阅读
- chrome-web-store - Chrome 扩展打开多个标签
- machine-learning - 什么是用来训练自注意力机制的?
- java - 为什么异常日志会使用相同的代码更改打印位置?
- python - 魔术方法 __str__ 不调用 str 调用
- python - 从在线 xml 中获取价值
- scala - 在 EMR 环境中向 Spark 提交 JAR 时出现 FileNotFoundException (stderr & stdout)
- java - 麻烦在 MacOS Mojave 上安装 pymssql
- typescript - 如何防止使用 TypeScript 在构造函数中未定义成员?
- caching - 处理 Redis 缓存存储断开连接上的 Nest.js 应用
- javascript - 乘法循环不相乘