What’s different between lines 16 and 17?
#user input annual_salary = float(input("Enter your annual salary: ")) portion_saved = float(input("Enter the percent of your salary to save, as a decimal: ")) total_cost = float(input("Enter the cost of your dream home: ")) #static vars portion_down_payment = total_cost*.25 monthly_salary = annual_salary/12 r = .04 #annual rate of return months_to_save = 0 current_savings = 0 investment_return = current_savings * r / 12 while current_savings < portion_down_payment: #current_savings += (current_savings * r / 12) + (portion_saved * monthly_salary) # Line 16 current_savings += (investment_return) + (portion_saved*monthly_salary) # Line 17 months_to_save += 1 print("Number of months: ", months_to_save)
I tried running it through pythontutor and the variation happens on step 15 of execution, but I can’t quite figure out what’s different.
When you use
current_savings += investment_return, it adds the same amount of interest to
current_savings each time through the loop. That interest is equal to
current_savings * r / 12 calculated before you started the loop.
But when you use
current_savings += (current_savings * r / 12), you recalculate the interest each time through the loop. So the interest is calculated based on the current value of
current_savings, which gets bigger each time the loop runs.