我正在写一个学费计划。我的问题/问题是:我如何才能获得四年的总数,而不是像我一样写出总数+ =(8240 + 8487.20 + 8741.82 + 9004.07)* 2

'''
CPS 313: Assignment 3, problem 3

At one college, the tuition for a full time student
is $8,000 per semester. It has been announced that the
tuition will be increased by 3% each year for the next 5 years.
Write a program with a loop that displays the projected semester
tuition amount for the next 5 years, and the total cost of 4
years' worth of tuition starting from now.
'''

def main():
    tuition = 8000.00
    total = 0

    print("Year\t", "Tuition per semester")

    for i in range(1,6):
        #Tuition increased by 3% each year for the next 5 years
        tuition += tuition*0.03
        #Displays tuition fee for each year
        print(i,'\t',format(tuition, '.2f'))

    total += (8240+8487.20+8741.82+9004.07)*2
    print("Total tuition in 4 years: $", format(total,\
          '.2f'),sep = '')

main()

'''
Output:
Year     Tuition per semester
1        8240.00
2        8487.20
3        8741.82
4        9004.07
5        9274.19
Total tuition in 4 years: $68946.18
'''

最佳答案

def main():
    tuition = 8000.00
    tuition_list = []
    total = 0

    for i in range(5):

        tuition += tuition*0.03
        tuition_list.append(tuition)

    for i, x in enumerate(tuition_list[:4]):
        print(f'Year {i+1}\tTuition ${round(x)}')

    print(f'Total for 4 years ${round(sum(tuition_list[:4]) * 2)}')


main()


每个学费都会被追加(添加)到列表中,因此最终会有5个元素的列表。

然后,我使用enumerate()遍历列表。这使我可以访问每个列表项,还可以创建一个索引号(0-5)。我使用list [:4]将列表限制为4。

然后,我只是在字符串中使用内联变量,因为这就是我喜欢的方式。我对列表求和,再次将其限制为前4个项目,然后将其乘以2。

输出:

>>> Year 1  Tuition $8240
>>> Year 2  Tuition $8487
>>> Year 3  Tuition $8742
>>> Year 4  Tuition $9004
>>> Total for 4 years $68946


编辑:

针对OP的评论。
您可以将4学费分配给像这样的变量

def main():
    tuition = 8000.00
    tuition_list = []

    tuition_yr1 = tuition * 1.03
    tuition_yr2 = tuition_yr1 * 1.03
    tuition_yr3 = tuition_yr2 * 1.03
    tuition_yr4 = tuition_yr3 * 1.03

    total_cost_over_4yrs = (tuition_yr1 + tuition_yr2 + tuition_yr3 + tuition_yr4) * 2

    print('Year 1', tuition_yr1)
    print('Year 2', tuition_yr2)
    print('Year 3', tuition_yr3)
    print('Year 4', tuition_yr4)
    print('Total over 4 years', total_cost_over_4yrs)

main()

10-06 05:19