Reputation: 109
I have been working on this simple interest calculator and I was trying to make the for loop iterate until the amount inputted by the user is reached. But I am stuck at the range part, if I assign a range value like range(1 ,11) it will iterate it correctly and print the year in in contrast to the amount but I want the program to iterate until the year in which principal is greater than the amount is reached. My current code is bellow and the final product I want to reach is also attached bellow the current code. I'm new to python so please bare with me if I'm of track. Thanks in advance.
Current code:
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();
Upvotes: 1
Views: 9389
Reputation: 2551
A suggestion for a more pythonic solution
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!")
Upvotes: 0
Reputation: 273
Instead, you can use a while loop. What I mean here is you can simply:
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()
Upvotes: 5