How to calculate compound interest in Python

1 Answer

0 votes
import math  # For math.pow

# Function to calculate compound interest
def calculate_compound_interest(principal, rate, years):
    if principal < 0 or rate < 0 or years < 0:
        print("Error: Principal, rate, and years must be non-negative values.")
        return -1

    # Calculate total amount using the compound interest formula
    amount = principal * math.pow(1 + rate / 100, years)

    # Return compound interest
    return amount - principal


principal = 100000
rate = 3.5
years = 5

compound_interest = calculate_compound_interest(principal, rate, years)

if compound_interest >= 0:
    # Display results with two decimal places
    print(f"Principal Amount: {principal:.2f}")
    print(f"Annual Interest Rate: {rate:.2f}%")
    print(f"Years: {years:.2f}")
    print(f"Compound Interest: {compound_interest:.2f}")
    print(f"Total Amount: {principal + compound_interest:.2f}")



'''
run:

Principal Amount: 100000.00
Annual Interest Rate: 3.50%
Years: 5.00
Compound Interest: 18768.63
Total Amount: 118768.63

'''

 



answered Aug 30 by avibootz
...