0

I am working through MIT OpenCourseWare and I have run into a problem with what should be a very simple function. The code below seems to work, but I get answers that are either correct for very close to what I should. For example, if you enter:

annual_salary = 120000
portion_saved = .10
total_cost = 1000000

It outputs 182, but the expected result is 183. However, if I enter:

annual_salary = 80000
portion_saved = .15
total_cost = 500000

I get 105, which is the expected result. If I remove the if branch and use the same inputs, I get 183 (correct) and 106 (incorrect). I am completely baffled.

def calc_savings(annual_salary, portion_saved, total_cost):
    portion_down_payment = .25
    r = 0.04 # return on investment
    monthly_salary = annual_salary / 12
    num_months = 1
    current_savings = 0

    while current_savings < total_cost * portion_down_payment:
        pre_interest = current_savings + (monthly_salary * portion_saved)
        current_savings = pre_interest + (pre_interest * r / 12)
        if current_savings >= total_cost * portion_down_payment:
            return num_months
        num_months += 1
    return num_months
    
annual_salary = int(input("Enter your annual_salary: "))
portion_saved = float(input("Enter the percent of your salary to save, as a decimal: "))
total_cost = int(input("Enter the cost of your dream home: "))

print("Number of months: ", calc_savings(annual_salary, portion_saved, total_cost))

1 Answer 1

1

If you add the investment return (current_savings * r / 12) and then add the monthly investment (monthly_salary * portion_saved) it will return the correct answers. You just need to switch the order you add them.

Sign up to request clarification or add additional context in comments.

1 Comment

Ahhh, I see. I’m trying to gain interest on the money I just deposited...I knew it would be something simple and boneheaded. Thanks for the answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.