将公式分配给变量与执行计算 in-line 会使用 while 循环更改我的脚本的结果。为什么?

Assigning formula to variable vs performing calulation in-line changes the outcome of my script using a while loop. Why?

我遇到了一个问题,我认为这与我的方程式中的错误无关,但与 Python 处理信息的方式有关。不明白,希望有人能解释一下。

以下是 MIT OCW 6.0001 中的一个问题,其中一个程序计算为某人的梦想家园存钱所需的月数。该问题假设我们谨慎投资并实现 return 每年 4% 的储蓄率。这就是变量 r。当用户输入 120000、.1 和 1000000.

时,该程序应通过生成结果 183 个月来通过测试用例

这是我第一次尝试解决这个问题:

annual_salary = (float(input("What is your starting annual salary?")))
portion_saved = (annual_salary * (float(input("What porportion of your annual salary will you save? Please enter a percentage as a decimal:"))))/12
total_cost = (float(input("What is the cost of your dream home?")))

portion_down_payment = total_cost * 0.25
current_savings = 0.0
r = 0.04
monthly_return = ((current_savings*r)/12)
months = 0.0

while current_savings < portion_down_payment:
    current_savings += portion_saved + monthly_return
    months += 1
print("Number of months:", months)

它没有通过测试用例。我已将问题缩小到 monthly_return 函数。如果我 运行 通过打印 monthly_returnwhile months < 2:

进行测试
annual_salary = (float(input("What is your starting annual salary?")))
portion_saved = (annual_salary * (float(input("What porportion of your annual salary will you save? Please enter a percentage as a decimal:"))))/12
total_cost = (float(input("What is the cost of your dream home?")))

portion_down_payment = total_cost * 0.25
current_savings = 0.0
r = 0.04
monthly_return = ((current_savings*r)/12)
months = 0.0

while months < 2:
    current_savings += portion_saved + monthly_return
    months += 1
print("Number of months:", months)
print(monthly_return)

我发现 return 等于 0.0。

但是,如果我简单地删除我为计算 monthly_return 而创建的变量,而是将其中包含的公式粘贴到脚本中的 space 中,我不仅会发现它通过了测试用例,但每月 return 计算也会 return ~6.68 而 months < 2.

annual_salary = (float(input("What is your starting annual salary?")))
portion_saved = (annual_salary * (float(input("What porportion of your annual salary will you save? Please enter a percentage as a decimal:"))))/12
total_cost = (float(input("What is the cost of your dream home?")))

portion_down_payment = total_cost * 0.25
current_savings = 0.0
r = 0.04
months = 0.0

while months < 2:
    current_savings += portion_saved + ((current_savings*r)/12)
    months += 1
print("Number of months:", months)
print(((current_savings*r)/12))

我不得不相信这里发生的事情与 Python 在执行 while 循环时读取每个变量的方式有关,但我不明白发生了什么或为什么.能解释一下吗?

您需要在 while 循环中更新这些值:

# Example data
annual_salary = 120000.0
portion_saved = annual_salary * (0.1)/12
total_cost = 1000000.0

portion_down_payment = total_cost * 0.25
current_savings = 0.0
r = 0.04
months = 0.0

while current_savings < portion_down_payment:
    portion_down_payment = total_cost * 0.25
    monthly_return = ((current_savings*r)/12)
    current_savings += portion_saved + monthly_return
    months += 1
print("Number of months:", months)

输出:

Number of months: 183.0

因为值 portion_down_paymentmonthly_return 需要在 while 循环的每次迭代中更新。而不是被分配一次。