Why is my Python While Loop Executing More than Necessary?

17 hours ago 5
ARTICLE AD BOX

I'm having a small issue with the following Python code, which is supposed to use a while loop and give me the amount of time in years it will take an investment to double at a given annual interest rate.

initialInvestment = 10 intRate = 2 newBalance = initialInvestment years = 0 if initialInvestment > 0: # Make sure user has a valid investment balance while newBalance < (2 * initialInvestment): newBalance += (newBalance * (intRate/100)) # Update balance years += 1 print(f'At {years} year(s), you would have ${newBalance:,.2f}') else: print(f'Please enter an investment amount greater than zero.') print(f'It would take {years} years to double your investment of ${initialInvestment:,.2f} at {intRate}%."')

I have been using the print statement within the while loop to track the balance and years, and I noticed that the code is adding an extra year before exiting. For example, I've used $10 as my initial investment and 2% as the interest rate. The print statement shows at 35 years the newBalance is $20, exactly double the initialInvestment, but the loop executes one more time. I even changed the condition to say while ... and newBalance != (2 * initialInvestment) and the code did not stop at 35 years.

Admittedly, I don't need to track the annual balance, so I could initialize years to -1, but I would rather understand what the issue is and how to correct it.

Read Entire Article