Python Program for Simple Interest
The task of calculating Simple Interest in Python involves taking inputs for principal amount, time period in years, and rate of interest per annum, applying the Simple Interest formula and displaying the result. For example, if p = 1000, t = 2 (years), and r = 5%, the Simple Interest is calculated using the formula and resulting in Simple Interest = 100.0.
Simple interest formula :
Simple Interest = (P x T x R)/100
Where:
- P is the Principal amount
- T is the Time period (in years)
- R is the Rate of interest per annum
Using function
Defining a function to calculate Simple Interest enhances readability and reusability. It is ideal when the calculation needs to be performed multiple times with different values. By calling the function with desired inputs, we get results without duplicating code, making the program cleaner and easier to maintain.
# function definition
def fun(p, t, r):
return (p * t * r) / 100
# given values for principal (p), time (t) in years and rate of interest (r) per annum
p, t, r = 8, 6, 8
# function calling
res = fun(p, t, r)
print(res)
Output
3.84
Explanation: In this example we defines a function called fun that calculates simple interest based on three input values: principal (p), time (t) in years, and rate of interest (r) per annum. The function returns the result of the simple interest formula.
Table of Content
Using lambda function
lambda function is useful for quick, single-line calculations like Simple Interest without defining a separate function. It helps in making the code compact and concise, but may reduce readability if the logic becomes complex.
# lambda function
si = lambda p, t, r: (p * t * r) / 100
# given values for principal (p), time (t) in years, and rate of interest (r) per annum
p, t, r = 8, 6, 8
res = si(p, t, r)
print(res)
Output
3.84
Explanation: lambda p, t, r: (p * t * r) / 100 takes three parameters: p (principal), t (time in years) and r (rate of interest per annum). It calculates Simple Interest and returns the result.
Using list comprehension
List comprehension allows us to generate lists in a single line of code using a simple syntax. While it is generally used to build lists from existing iterables, it can sometimes be creatively used for quick calculations though this is more of a trick than a recommended practice.
# given values for principal (p), time (t) in years, and rate of interest (r) per annum
p, t, r = 8, 6, 8
si = [p * t * r / 100][0]
print(si)
Output
3.84
Explanation : si = [p * t * r / 100][0] calculates Simple Interest using formula and places the result in a list as a single element and accesses it using [0] to get the calculated interest.