Calculate Compound Interest in Python
A = P(1 + R/100n)^(nT). Then interest is A minus P. The ** is the whole point.
BeginnerBasic Python ProgramsExample 13 of 25
calculate-compound-interest.py
1# Program to calculate compound interest23principal = float(input("Enter principal amount: "))4rate = float(input("Enter annual interest rate (in %): "))5time = float(input("Enter time in years: "))6n = int(input("Enter number of times interest applied per year: "))78amount = principal * (1 + rate / (100 * n)) ** (n * time)9compound_interest = amount - principal1011print("Compound Interest is:", compound_interest)12print("Total Amount is:", amount)
Output
Enter principal amount: 1000 Enter annual interest rate (in %): 5 Enter time in years: 2 Enter number of times interest applied per year: 4 Compound Interest is: 104.486... Total Amount is: 1104.486...
In this one
- ** is power, ^ is XOR
- print A - P, not just A
What's going on
Simple interest is a multiply. Compound interest is a power.
A = P * (1 + R/(100*n)) ** (n*T)
n is "how many times a year". Quarterly → 4. Forget it and you are back to simple-ish interest.
Interest is A - P, not A. Printing only the amount makes people think they earned 1104 rupees on a 1000 principal.
** is exponent. ^ is XOR. Use the wrong one and you get a mystery integer.
After this program
If the idea is still fuzzy, read Day 1: Introduction to Python in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 basic python programs, or see every topic on Python exercises.