我一直在研究这个简单的兴趣计算器,我试图让 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();
答案 0 :(得分:4)
相反,您可以使用 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()