The following code snippet attempts to calculate the balance of a savings account with an annual interest rate of 5% after 4 years, if it starts with a balance of $100.
>>> balance = 100
>>> def add_interest(balance, rate):
... balance += balance * rate / 100
...
>>> for year in range(4):
... add_interest(balance, 5)
... print('Balance after year {}: ${:.2f}'.format(year+1, balance))
...
Balance after year 1: $100.00
Balance after year 2: $100.00
Balance after year 3: $100.00
Balance after year 4: $100.00
Explain why this doesn't work and provide a working alternative.
The problem is within the add_interest
function:
def add_interest(balance, rate):
balance += balance * rate / 100
This creates a new float
object, balance
, local to the function, which is independent of the original balance
object. When the function exits, the local balance
is destroyed and the original balance
never updated. One fix would be to return
the updated balance value from the function:
>>> balance = 100
>>> def add_interest(balance, rate):
... balance += balance * rate / 100
... return balance
...
>>> for year in range(4):
... balance = add_interest(balance, 5)
... print('Balance after year {}: ${:.2f}'.format(year+1, balance))
...
Balance after year 1: $105.00
Balance after year 2: $110.25
Balance after year 3: $115.76
Balance after year 4: $121.55