doulikepeaches
doulikepeaches

Reputation: 69

Why do I need to define variables in my while loop for my code to work?

This is a question from the 6.0001 MIT Intro to CS course PS1-C: Why do I have to define certain variables twice - both inside and outside the while loop when the definition isn't changing? For example, diff_from_target or current_savings variable.

Full code below:

# User inputs
total_cost = 1000000
starting_annual_salary = 300000
semi_annual_raise = .07

# bisection search
low = 0
high = 10000
steps = 0

# Investments (investment = current_savings * monthly rate)
r = .04
monthly_rate = r/12

# Calculate down payment (target savings)
target_savings = .25 * total_cost
current_savings = 0

diff_from_target = target_savings - current_savings
savings_rate = (low+high)/2

while abs(diff_from_target) > 100 and steps < 100:
    months = 0
    current_savings = 0
    annual_salary = starting_annual_salary
    savings_rate = (low+high)/2

    while months < 36:
        current_savings += (annual_salary/12)*savings_rate + current_savings * monthly_rate
        months += 1
        if months % 6 == 0:
            annual_salary += annual_salary * semi_annual_raise

    diff_from_target = target_savings - current_savings

    if diff_from_target > 0:
        low = savings_rate
    elif diff_from_target < 0:
        high = savings_rate

    steps +=1

else:
    if abs(diff_from_target) <= 100:
        print("%: {0:.4f}, steps: {1}".format(savings_rate, steps))
    else:
        print("Not possible to 36 months")

Upvotes: 0

Views: 63

Answers (1)

Lcj
Lcj

Reputation: 451

This is probably to make sure that the variable current_savings exists after the loop even if the loop didn't run a single time (for example if one of the conditions was False at the beginning)

Upvotes: 1

Related Questions