如何在Python for循环中迭代直到满足条件

sar*_*ave 1 python loops

我一直在研究这个单利计算器,我试图让 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();
Run Code Online (Sandbox Code Playgroud)

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

小智 5

相反,您可以使用 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()
Run Code Online (Sandbox Code Playgroud)