Back to: Python Programming
0
Calculating the interest earned or paid on an investment or loan requires some user data and a formula. We can use Python to do the calculations.
The Compound Interest Formula:

For this exercise we’ll need to ask the user to enter the:
- principal (P) amount they want to invest
- what the interest rate (r – as a decimal) is
- how often we’ll be compounding (n – if compounding daily, n is 365)
- the number of years (t).
These numbers are put into the formula to find:
- amount in the bank at the end of the time.
How would we extend this to find the Interest earned (I)?
Solution:
# Python Compound Interest Calculator
# By Mr. Dickinson
# Ver: 1.0
# Declare the four variables
principle = 0
rate = 0
compounding_period = 365 # <-- Assumes daily
time = 0
# For Input Validation we use a While Loop
# The While Loop prompts user to enter a (+)ve number
while principle <= 0:
principle = float(input("Enter the amount to invest: "))
if principle <= 0:
print("Principal must be greater than zero!")
# Use a While Loop to prompt user to enter a (+)ve number
while rate <= 0:
rate = float(input("Enter the interest rate: "))
if rate <= 0:
print("Rate must be a positive number!")
# Use a While Loop to prompt user to enter a (+)ve number
while time <= 0:
time = float(input("Enter investment time in years: "))
if time <= 0:
print("Time must be greater than zero!")
#total = principle * pow(1 + rate/(100*compounding_period), (compounding_period * time))
total = principle * ((1 + rate/(100*compounding_period)) ** (compounding_period * time))
print(f"Your balance after {time} years compounded daily at")
print(f"an interest rate of {rate}% will be ${total:.2f}")
Note in the calculation, we can bring one value to the power of another using multiple techniques:
x = yz
- x = pow(y, z) or
- x = y ** z
Basic: Extend this code to specify the amount of interest earned at the end of the period.
Advanced: Extend the code to allow the user to specify if the investment is compounded daily (365), weekly (52), monthly (12) or annually (1).