Calculate simple and compound interest in Python
If you are working on a finance application or some mathematical solutions then you may have a requirement to calculate the simple or compound interest. In this post, we will explain to calculate them one by one.
Let's check the mathematical formulas of simple and compound interest.
Simple Interest = (principal * time * rate) / 100
Compound Interest = principal((1 + rate / 100)time - 1)
Calculate the simple interest
We will calculate the simple interest using Python code here. We will use "*" and "/" arithmetic operators of Python to calculate that. We will be using the above Simple Interest formula for the calculation. Let's check the Python program to understand it.
# input values required
principal_amount = 10000
time = 4
rate_of_interest = 14
# calculate the simple interest
simple_interest = (principal_amount * time * rate_of_interest)/100
print("Simple interest is: ", simple_interest)
Output
Simple interest is: 5600.0
In the above Python code example
- We have defined three variables that will be used to calculate the simple interest in Python - principal_amount, time, and rate_of_interest.
- Using the code - (principal_amount * time * rate_of_interest)/100, we are calculating the simple interest and assigning the result to the simple_interest variable.
- Print the result - simple_interest.
Calculate the compound interest
The compound interest can be calculated in Python using two methods. The first is that we use "*", "/" and "**" operators and the second is using "*", "/" and pow() function. We will be using the mathematical formula of Compound Interest to calculate it in Python.
# Example 1
# input values required
principal_amount = 10000
time = 4
rate_of_interest = 14
# calculate the simple interest
compound_interest = principal_amount * ((1 + rate_of_interest / 100)**time - 1)
print("Compound interest is: ", compound_interest)
Output
Compound interest is: 6889.601600000008
# Example 2: Using pow() function
# input values required
principal_amount = 8000
time = 4
rate_of_interest = 13.25
# calculate the compound interest
amount = principal_amount * (pow((1 + rate_of_interest / 100), time))
compound_interest = amount - principal_amount
print("Compound interest is: ", compound_interest)
Output
Compound interest is: 5159.604275312504
Full Code Example
- Calculate the square root of a number in python
- Calculate the factorial of a number using python code
- [Python] Simple yield generator example
- Create pandas DataFrame and add columns and rows to it
- [Python] The get() method on Python dicts and its "default" arg
- Python - regex,replace all character exept A-Z a-z and numbers
- [Python] Pytest fixture example with cleanup and teardown