HI,

I have written a small program that uses a while loop to calculate how many years it takes for an investment to double given an interest rate:

However, I think there is something minor wrong with the calculation for years, since when testing I put in 100% it should say 1 year, yet says it takes 2 years.

def main():
    # Introduction
    print __doc__
        
    presVal = 1 # Set present value to $1
    intRate = input("Enter the Interest Rate >>") # Ask for the Interest Rate
    years = 0 # Start the years at zero
    futVal = presVal # Set the variable used to accumulate

    # Set the while loop
    while futVal <= presVal *2: # Continue 'while' futVal has not doubled
        futVal = futVal + futVal *((float(intRate)/100)) # Calc the next loop
        years = years + 1 # Add 1 to the years

    # Calculate the amount left of the part year
    fut = futVal%2
 
    # Print the answer   
    print            
    print "It takes approximately %0.2f years to double the present value" % (years-fut)

Any help would be most welcomed.

Member Avatar for Mouche
while futVal <= presVal *2

should be

while futVal < presVal *2

Right now, when the value is doubled, it still executes the loop once more.

With this change, you get an answer of "1.00 years."

Thank you. Stupid mistake I guess...

Simpler program:

you should type line by line so the indents come into it

#A program to determine how long it takes for an investment to double
def main():
    I=input("What is the annualized interest rate as a decimal?: ")
    i=0
    z=1
    while z<2:
        i=i+1
        z=(z*(1+I))
    if z>=2:
        print i
main()
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.