Krishna Nalla
Krishna Nalla

Reputation: 1

Calculating Total from interest, principle and years using FOR LOOP

I am trying to create a program that asks the user their principal, interest rate, and total amount of years. I want my program to show them the amount of total return they would expect for each year. I want it to start at year 1. When I run my script, it only shows one year's worth total interest. Here is what I have so far.

#Declare the necessary variables.
princ = 0
interest = 0.0
totYears = 0
year = 1

#Get the amont of principal invested.
print("Enter the principal amount.")
princ = int(input())

#Get the interest rate being applied.
print("Enter the interest rate.")
interest = float(input())

#Get the total amount of years principal is invested.
print ("Enter the total number of years you're investing this amonut.")
totYears = int(input())

for years in range(1, totYears):
    total=year*interest*princ
    years += 1

print (total)

Thank you any help is appreciated.

Upvotes: 0

Views: 1295

Answers (1)

Prune
Prune

Reputation: 77857

There are problems here:

for years in range(1, totYears):
    total=year*interest*princ
    years += 1

print (total)
  1. You change years within the loop. Don't. The for statement takes care of that for you. Your interference makes years change by 2 each time through the loop.
  2. Every time through the loop, you throw away the previous year's interest and compute a new one. Your print statement is outside the loop, so you print only the final value of total.
  3. Your loop index is years, but you've computed on the variable year, which is always 1. A programming technique I picked up many years ago is never to use a plural variable name.

Perhaps you need this:

for years in range(1, totYears):
    total = years * interest * princ
    print (total)

Upvotes: 1

Related Questions