Reducing amount of code required for interest calculations

Viewed 39

I have two functions that calculate the balance after a year and the final balance after 'N' number of years (compound interest). Is there a more efficient way to do this/ way to do it with less code?

def balance_after_a_year(init_sum, interest_rate):
    return init_sum * (100 + interest_rate) / 100

def final_balance(init_sum, interest_rate, years):
    final_sum = init_sum
    for i in range(years):
        round_num = round(balance_after_a_year(final_sum, interest_rate), 2)
    return round_num 
1 Answers

You can create a single function that does compound interest and then pass the number of years as 1 to find the interest rate after 1 year. E.g:

#compund interest = starting_amount * (interest_rate)^n.

def get_final_amount(inital_sum,interest_rate,compounding_periods):
  interest_rate = 1+(interest_rate/100)
  final_amount = round(inital_sum * (interest_rate)**compounding_periods,2)
  return final_amount


print(get_final_amount(4500,4,3))

where the interest rate is entered as its percentage value so in the example it is the value of $4,500 at an interest rate of 4% for 3 years.

Related