python - 如何迭代直到在python for循环中满足条件
问题描述
我一直在研究这个简单的利息计算器,我试图让 for 循环迭代,直到达到用户输入的金额。但是我被困在范围部分,如果我分配一个范围值,如 range(1 ,11) 它将正确迭代它并打印与金额相反的年份,但我希望程序迭代直到本金所在的年份大于达到的金额。我当前的代码如下,我想要达到的最终产品也附在当前代码的下方。我是 python 新手,所以如果我知道的话,请和我一起裸露。提前致谢。
当前代码:
principal = float(input("How much money to start? :"))
apr = float(input("What is the apr? :"))
amount = float(input("What is the amount you want to get to? :"))
def interestCalculator():
global principal
year = 1
for i in range(1, year + 1):
if principal < amount:
principal = principal + principal*apr
print("After year " + str (i)+" the account is at " + str(principal))
if principal > amount:
print("It would take" + str(year) + " years to reach your goal!")
else:
print("Can't calculate interest. Error: Amount is less than principal")
interestCalculator();
解决方案
相反,您可以使用 while 循环。我的意思是你可以简单地:
principal = float(input("How much money to start? :"))
apr = float(input("What is the apr? :"))
amount = float(input("What is the amount you want to get to? :"))
def interestCalculator():
global principal
i = 1
if principal > amount:
print("Can't calculate interest. Error: Amount is less than principal")
while principal < amount:
principal = principal + principal*apr
print("After year " + str (i)+" the account is at " + str(principal))
if principal > amount:
print("It would take" + str(year) + " years to reach your goal!")
i += 1
interestCalculator()
推荐阅读
- android - 嵌套在 CardView 中的 Android ImageView - 不显示圆角
- html - Github 页面不起作用,它只显示存储库名称
- javascript - Ajax 似乎比我发送的加载更多
- c - 我可以轻松地将字符串嵌入到原始二进制文件中吗?
- lotus-domino - HTTP Web 服务器:IBM Notes 异常 - 在索引中找不到条目
- python - 如何使用 ari-py 从端点获取 sip 对等方列表
- javascript - 为什么 mongoose 的 deleteOne 和 findById 对已删除的 id 起作用
- excel - 条件格式以突出显示过去和未来的日期
- angular - Dialogflow 中的 Angular 元素
- r - 如何在 R 数据框中的最后一行添加总列,其值为 %