 # Solved: Compound interest exercise not working for n = 1

#1

Can someone please help tell me what is wrong here? The lab is telling me to review whether the code for case n=1 is right. I’m getting the right output for test case n = 1 so I’m not sure what is wrong.

``````def compound_interest(principle, rate, years):
rate = float(rate)/100
years = int(years)
interest = 0
total_interest = 0
newprinciple = principle
principle = principle
year = 1
while year <= years:
if year == 1:
interest = principle * rate
newprinciple = principle + interest
total_interest = total_interest + interest
year = year + 1
else:
interest = newprinciple * rate
newprinciple = newprinciple + interest
total_interest = total_interest + interest
year = year + 1
print(total_interest)

compound_interest(100,5,1)``````

#2

Hi Gopi,

You approach is correct just that instead of printing it is supposed to return the value.

#3

Thank you that worked. I changed print to return and it worked

#4

Solved:

``````def compound_interest(principle, rate, years):
rate = float(rate)/100
years = int(years)
interest = 0
total_interest = 0
newprinciple = principle
principle = principle
year = 1
while year &lt;= years:
if year == 1:
interest = principle * rate
newprinciple = principle + interest
total_interest = total_interest + interest
year = year + 1
else:
interest = newprinciple * rate
newprinciple = newprinciple + interest
total_interest = total_interest + interest
year = year + 1
return (total_interest)

compound_interest(100,5,1)``````

#5

Here is a more crisper version of the solution:

``````def compound_interest(principle, rate, years):
np = principle
for i in range(years):
np += np * rate / 100
return (np - principle)``````

#6

Thanks @Kamal_Upadhyay for the neat version

I have just updated the code to fix the indentation so that we can copy-paste in the notebook as it is.

#7

Thank you Kamal. Great solution.