【问题标题】:Starting 2nd for loop based on first基于第一个开始第二个 for 循环
【发布时间】:2016-10-14 15:38:49
【问题描述】:

我正在尝试编写一个程序来计算学费的未来价值。今天的学费是 10000 美元,每年增长 5%。我正在尝试编写一个程序,告诉我 10 年的学费,以及 10-13 年的总学费。

我几乎可以肯定我在编写 2 个 for 循环时走在正确的轨道上,但我的程序不会运行。

def tuition():

    tuition_cost=10000
    increase=1.05
    running_total=0

#first loop includes tuition for years 1-10 
#update tuition for year 10
    for year in range (1,11,1):
        tuition_cost=((tuition_cost*(increase**year))

    print(tuition_cost)

    for year in range (10,14,1):
        tuition_cost=(tuition_cost*(increase**year))
        running_total=running_total+tuition_cost

    print(running_total)

tuition()   

有人有什么建议吗?

【问题讨论】:

  • 不会运行?它什么都不做吗?它会引发一些错误吗?
  • tuition_cost=((tuition_cost*(increase**year)) 行缺少括号
  • 由于我的第一个 forloop 中的额外括号,起初它给出了一个语法错误。在我修复它之后,它会运行,但会给出 140,000 和 275,000 的错误结果。答案应该是大约 16000 美元和 70000 美元
  • 我相信你的问题是你更新了所有 10 次的学费...意思是,在循环的第一遍,你随着第一年的增加而更新值,然后你更新它,然后在第二遍中更新如果前两年...如果您删除 "*year 部分,我相信您会得到一些明智的。
  • 不正确的结果是因为您正在重新分配tuition_cost,但计算时好像tuition_cost 仍然是10000。您可以找到1000*(1.05**year) 或者您可以每年做tuition_cost = tuition_cost*1.05,但是两者都做会给你错误的答案

标签: python for-loop nested nested-loops


【解决方案1】:

试试这个:

def tuition():
    tuition_cost=10000
    increase=1.05

    print('the cost for the year 10:', tuition_cost*(increase**10))

    running_total = 0
    for year in range(10):
        running_total += tuition_cost*(increase**year)

    print('the cost for 10 years:', running_total)

    for year in range(10,14,1):
        running_total += tuition_cost*(increase**year)

    print('the cost for 14 years:', running_total)

tuition()   

【讨论】:

  • def学费():​​学费_成本=10000增加=1.05运行总=0#第一个循环包括1-10年的学费#更新10年的学费范围(1,11,1):学费=(tuition_cost*(increaseyear)) print(tuition) for year in range (10,14,1): 学费=(tuition*(increaseyear)) running_total=running_total+tuition print( running_total) 学费()
【解决方案2】:

我想,你的程序应该是这样的:

tuition_cost = 10000
increase = 1.05
running_total = 0

for year in range(0, 11):
    price_for_year = tuition_cost*(increase**year)
    print(price_for_year)

for year in range(10, 14):
    running_total += price_for_year
    price_for_year = tuition_cost*(increase**year)
    print(running_total)

【讨论】:

    猜你喜欢
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    相关资源
    最近更新 更多