如何找到文件处理中的平均值之和

所以..这个项目我需要一些帮助。我开始学习一些关于 python 的知识,我们的讨论是关于文件处理的。我做了正确的执行,但这里的问题是我需要找到给定循环的总和和平均值。


def num3():

    ifile = open(r'sales.txt','w')

    no_days = 7

    for count in range(1, no_days+1):

         print('List of Sales in Php')

         sales = float(input('Day' +str(count)+ ':\tPhp'))

         ifile.write(str(sales)+'\n')

         

   ifile.close()

num3()


翻翻过去那场雪
浏览 90回答 2
2回答

慕慕森

这应该工作:def num3():    with open('sales.txt','w') as fp:        no_days = 7        print('List of Sales in Php')        total = 0        for count in range(1, no_days+1):            sales = float(input('Day' +str(count)+ ':'))            total += sales        total = total        average = total/no_days        fp.write(f'Total Value: {total}\nAverage Value: {average}')            num3()

一只甜甜圈

您需要将销售额计算在一个单独的变量中。然后除以 no_days:ifile = open(r'`enter code here`sales.txt', 'w')no_days = 7total_sales = 0for count in range(1, no_days + 1):    print('List of Sales in Php')    sales = float(input('Day' + str(count) + ':\tPhp'))    total_sales += sales    ifile.write(str(sales) + '\n')ifile.close()print(f"sum={total_sales}")print(f"average={total_sales / no_days}")
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python