'''calculate the future value of an investment after 10 years''' 

def calcValue( initialValue, interestRate ): 
    period = 10 
    investmentValue = initialValue 

    for i in range(period): 
        investmentValue = investmentValue * ( 1 + interestRate ) 

    return investmentValue 

def main(): 
    principal = int(raw_input("Enter initial investment amount: ")) 
    interest = float(raw_input("Enter interest rate as a percentage: ")) / 100 

    finalValue = calcValue( principal, interest ) 
    print "Final value of the investment is $%0.2f" % finalValue 

main()

i need to modify this program so that a user can specify the period of invest and so the user can make additional yearly investments.

i'm just unsure how to approach the question

Any sugesstions?

Dani AI

Generated

A couple of practical ways to extend the original script so a user can pick the number of years and add yearly investments: (1) iterate year by year, which makes it easy to control whether the extra payment is applied at the start or end of each year; or (2) use the closed-form annuity formula for speed. Below is a compact, safe iterative function plus a formula version and a few tips. This follows 's suggestion to make the period an input and builds on 's original idea. Examples use Python 3.

def future_value(principal, annual_rate, years, yearly_contrib=0.0, contrib_at_start=False):
    fv = float(principal)
    r = float(annual_rate)
    for _ in range(int(years)):
        if contrib_at_start:
            fv += yearly_contrib
        fv = fv * (1 + r)
        if not contrib_at_start:
            fv += yearly_contrib
    return fv

A closed-form alternative for end-of-year contributions: FV = P*(1+r)*n + C(((1+r)*n - 1)/r). For contributions at the start of each year multiply the annuity term by (1+r). Handle r == 0 separately (FV = P + Cn). Quick tips: validate inputs (years >= 0, rate >= 0), decide if contributions happen before or after interest for accurate results, and consider using Decimal for exact currency math if you need strict 2-decimal correctness.

Recommended Answers

All 4 Replies

See how period is used and how it's use can become similar to other values in the formula.

Tony

See how period is used and how it's use can become similar to other values in the formula.

Tony

So to take the period = 10 out and turn it into raw_input ??

actually i think ive worked it out

Thanks tony
:)

Can you mark solved or tell what is still unclear/post results?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.