In this post, we will investigate how we can calculate simple interest and compound interest in Python with the linguistic structure of the program.
Before jumping to the programming section let us discuss the mathematical formula to calculate the simple interest and compound interest with the algorithm as shown below.
Algorithm to calculate simple interest and compound interest
Step 1: Start
Step 2: Input Principal, Time and Rate
Step 3: Simple Interest; SI = (P * T * R) / 100
Step 4: Compound Interest; CI = P * ((1 + R/100) ** T -1)
Step 5: Display Simple Interest; SI and Compound Interest; CI
Step 6: Stop
Also Read: Python Program with Conditional Statements
Program to calculate simple interest and compound interest in python
#Input P = input("\n Enter the principal amount: ") T = input("\n Enter the time: ") R = input("\n Enter the rate: ") #Process Si = (int(P) * float(T) * float(R) ) /100 Ci = int(P) * (((1 + float(R)/100) ** int(T)) - 1) #Output print("\n Simple Interest = ",Si) print("\n Compound Interest = ",Ci)
Note: In order to execute this program, save it with a suffix of .py, for example, HelloWorld.py – Ctrl+F5
(for Visual Studio Code IDE). According to different Integrated Development Environments (IDEs), the process to run the program may differ, no need to worry about it.
Output
Enter the principal amount: 1200
Enter the time: 3
Enter the rate: 4
Simple Interest = 144.0
Compound Interest = 149.8368000000001
Explanation
Firstly, we started our code with the comment Input beginning with the special character called hash “#“. After that we took 3 variables; P, T and R for the input of Principal Amount, Time and Rate respectively from the user.
P = input("\n Enter the principal amount: ")
T = input("\n Enter the time: ")
R = input("\n Enter the rate: ")
The values entered by the user are stored in the variables P, T and R as required per the program.
After that, we encountered to the processing part or heart area of the program where we performed the actual mathematical calculation with the formula of simple interest and compound interest. And we stored the formula or the operation in two different variables; Si and Ci for Simple Interest and Compound Interest respectively as shown below.
Si = (int(P) * float(T) * float(R) ) /100
Ci = int(P) * (((1 + float(R)/100) ** int(T)) - 1)
However, the above assigned expression is the simplest method to assign the formula and can be modified in any way. Likewise, for Si variable we can split it into other variable and then finally integrate them to perform calculation.
Let’s take a quick look on it.
A = int(P)
B = float(T)
C = float(R)
Si = (A * B * C) / 100
As a result, there will be a slight difference in the execution speed of the program. Inspite of being different in appearance but the behavior is similar to both of them.
Finally, we get the required Simple Interest and the Compound Interest on the output screen.