繁体   English   中英

如何迭代直到满足python for循环中的条件

[英]How to iterate until a condition is met in python for loop

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

一个更pythonic解决方案的建议

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(principal, apr, amount):
    year = 0
    yield year, principal
    while principal < amount:
        year += 1
        principal += principal*apr
        yield year, principal


for year, amount in interestCalculator(PRINCIPAL, APR, AMOUNT):
    print(f"After year {year} the account is at {amount:.2f}")

if year == 0:
    print("Can't calculate interest. Error: Amount is less than principal")
print(f"It would take {year} years to reach your goal!")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM