首页 > 解决方案 > 如何迭代直到在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();

最终预期结果:
在此处输入图像描述

标签: pythonloops

解决方案


相反,您可以使用 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()

推荐阅读