【问题标题】:Why do I need to define variables in my while loop for my code to work?为什么我需要在我的 while 循环中定义变量才能让我的代码工作?
【发布时间】:2020-08-09 16:06:21
【问题描述】:

这是 6.0001 MIT Intro to CS course PS1-C 中的一个问题: 为什么我必须两次定义某些变量——当定义没有改变时,在while循环内部和外部?例如,diff_from_targetcurrent_savings 变量。

完整代码如下:

# 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")

【问题讨论】:

  • 我猜这是代码通过else部分的情况

标签: python variables scope


【解决方案1】:

这可能是为了确保变量 current_savings 在循环之后存在,即使循环没有运行一次(例如,如果其中一个条件在开始时为 False)

【讨论】:

  • 正确(并且我删除了我之前的错误评论)
  • 不正确,因为 current_savings 在 while 循环之外没有被引用。唯一相关的变量是diff_from_targetstepssavings_rate。前两个必须事先定义,因为它们在 while-loop 测试中使用。
猜你喜欢
  • 2012-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-15
  • 1970-01-01
相关资源
最近更新 更多