Python Program to Calculate Simple Interest
simple_interest = (principal * rate * time) / 100, where principal is the initial amount, rate is the interest rate, and time is the time period in years.Examples
How to Think About It
Algorithm
Code
principal = float(input("Enter the principal amount: ")) rate = float(input("Enter the rate of interest: ")) time = float(input("Enter the time in years: ")) simple_interest = (principal * rate * time) / 100 print(f"Simple Interest: {simple_interest}")
Dry Run
Let's trace the example where principal=1000, rate=5, and time=2 through the code
Input principal
principal = 1000.0
Input rate
rate = 5.0
Input time
time = 2.0
Calculate simple interest
simple_interest = (1000.0 * 5.0 * 2.0) / 100 = 100.0
Print result
Output: Simple Interest: 100.0
| Variable | Value |
|---|---|
| principal | 1000.0 |
| rate | 5.0 |
| time | 2.0 |
| simple_interest | 100.0 |
Why This Works
Step 1: Input values
The program asks the user to enter the principal, rate, and time, which are needed to calculate simple interest.
Step 2: Apply formula
It uses the formula (principal * rate * time) / 100 to find the interest earned over the time period.
Step 3: Display output
Finally, it prints the calculated simple interest so the user can see the result.
Alternative Approaches
def calculate_simple_interest(p, r, t): return (p * r * t) / 100 principal = float(input("Enter principal: ")) rate = float(input("Enter rate: ")) time = float(input("Enter time: ")) interest = calculate_simple_interest(principal, rate, time) print(f"Simple Interest: {interest}")
import sys principal = float(sys.argv[1]) rate = float(sys.argv[2]) time = float(sys.argv[3]) simple_interest = (principal * rate * time) / 100 print(f"Simple Interest: {simple_interest}")
Complexity: O(1) time, O(1) space
Time Complexity
The calculation involves a fixed number of arithmetic operations, so it runs in constant time.
Space Complexity
Only a few variables are used to store inputs and the result, so space usage is constant.
Which Approach is Fastest?
All approaches run in constant time and space; using a function improves code clarity but does not affect performance.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Direct calculation | O(1) | O(1) | Simple scripts and quick calculations |
| Function-based | O(1) | O(1) | Reusable code and larger projects |
| Command line arguments | O(1) | O(1) | Automation and scripting without user interaction |