PythonMastery

Compound interest program in Python

Calculate compound interest with A = P(1 + r/100)^t, show the balance year by year, and compare yearly, monthly and daily compounding.

With compound interest, the interest for each year is added to the balance, and next year's interest is calculated on that larger balance. The amount after t years is A = P × (1 + r / 100)^t, where P is the principal and r is the yearly rate in percent.

The program

python
principal = float(input("Principal: "))
rate = float(input("Rate per year (%): "))
years = int(input("Time (years): "))

amount = principal * (1 + rate / 100) ** years
interest = amount - principal

print(f"Amount after {years} years = {amount:.2f}")
print(f"Compound interest       = {interest:.2f}")

Typed in this example: 10000, 7.5, 3. Press Run to type your own.

output
Principal: 10000
Rate per year (%): 7.5
Time (years): 3
Amount after 3 years = 12422.97
Compound interest       = 2422.97

How it works

Year by year

A loop shows the same result one year at a time:

python
principal = 10000
rate = 7.5

balance = principal
for year in range(1, 4):
    interest = balance * rate / 100
    balance += interest
    print(f"Year {year}: interest {interest:8.2f}, balance {balance:9.2f}")
output
Year 1: interest   750.00, balance  10750.00
Year 2: interest   806.25, balance  11556.25
Year 3: interest   866.72, balance  12422.97

The interest grows every year, because the balance it is calculated on grows.

Compounding n times per year

Many banks add interest monthly or daily instead of once a year. With n periods per year, each period uses the rate divided by n, and there are n * years periods: A = P × (1 + r / (100 × n))^(n × t).

python
principal = 10000
rate = 7.5
years = 3

for name, n in [("yearly", 1), ("half-yearly", 2), ("quarterly", 4), ("monthly", 12), ("daily", 365)]:
    amount = principal * (1 + rate / 100 / n) ** (n * years)
    print(f"{name:<12} {amount:9.2f}")
output
yearly        12422.97
half-yearly   12471.79
quarterly     12497.16
monthly       12514.46
daily         12522.94

More frequent compounding gives a little more money, but the increase gets smaller each time.

Learn the idea: Input & Output: Talking to Your User, Operators & Expressions