In: Computer Science
The formula for calculating the amount
of money in a savings account that begins with an initial principal
value (P) and earns annual interest (i) for (n) years is: P(1 +
i)n
Note that i is a decimal, not a percent interest rate: .1 NOT
10%
Write a python program that does the following:
Code:
import math
def calc_compound_interest():
    ''' Asks user to input principle, interest and years to invest
        and calculates the end value using power function of math library.
    '''
    principle = float()  # initialize principle
    int_rate = float()  # initialize int_rate
    years = int()  # initialize years
    while type(principle) != 'float' or type(int_rate) != 'float' or type(
            years) != 'int':  # Check if the user inputs are of the right type
        try:
            principle = float(input('Enter the principle amount: '))  # Prompts user for principle
            int_rate = float(input('Enter the rate of interest: '))  # Prompts user for rate of interest
            years = int(input('Enter the number of years to invest: '))  # Prompts user for years
            break;
        except:
            continue
    end_val = principle * pow((1 + int_rate), years)  # Calculate the end value
    return end_val
def calc_compound_interest_recursive():
    principle = float()  # initialize principle
    int_rate = float()  # initialize int_rate
    years = int()  # initialize years
    while type(principle) != 'float' or type(int_rate) != 'float' or type(
            years) != 'int':  # Check if the user inputs are of the right type
        try:
            principle = float(input('Enter the principle amount: '))  # Prompts user for principle
            int_rate = float(input('Enter the rate of interest: '))  # Prompts user for rate of interest
            years = int(input('Enter the number of years to invest: '))  # Prompts user for years
            break;
        except:
            continue
    # Calculates the end value
    for y in range(years):
        if y == 0:
            end_val = principle * (1 + int_rate)
        else:
            end_val = end_val * (1 + int_rate)
    return end_val
def main():
    pow_val = round(calc_compound_interest(), 2)  # Round upto 2 decimals
    base_val = round(calc_compound_interest_recursive(), 2)  # Round upto 2 decimals
    print(f'End Value using power function= {"{:,}".format(pow_val)}')  # Print using commas
    print(f'End Value without using power function= {"{:,}".format(base_val)}')  # Print using commas
main()
Output:

Keep asking for inputs until vaild input is entered:
