Search code examples
pythonloopscounter

Python: for loop with counter and scheduled increase in increase


Python Learner. Working on a recurring monthly deposit, interest problem. Except I am being asked to build in a raise after every 6th month in this hypothetical. I am reaching the goal amount in fewer months than I'm supposed to.

Currently using the % function along with += function

annual_salary = float(input("What is your expected Income? "))                  
portion_saved = float(input("What percentage of your income you expect to save? "))
total_cost = float(input("what is the cost of your dream home? "))
semi_annual_raise = float(input("Enter your expected raise, as a decimal "))

monthly_salary = float(annual_salary/12)
monthly_savings = monthly_salary * portion_saved
down_payment= total_cost*.25
           
savings = 0
for i in range(300):
    savings = monthly_savings*(((1+.04/12)**i) - 1)/(.04/12)
    if float(savings) >= down_payment:
            break
    if i % 6 == 0 :
        monthly_salary += monthly_salary * .03
        monthly_savings = monthly_salary * portion_saved

Solution

  • Does something like this work for you? Typically, we want to use while loops over for loops when we don't know how many iterations the loop will ultimately need.

    monthly_savings = 1.1 # saving 10% each month
    monthly_salary = 5000
    down_payment = 2500
    interest = .02
    savings = 0
    months = 0
    
    while savings < goal:
        print(savings)
        savings = (monthly_salary * monthly_savings) + (savings * interest)
        months += 1
        
        if months % 6 == 0 :
            monthly_salary += monthly_salary * .03
            
    print("Took " + str(months) + " to save enough")