首页 > 解决方案 > 如何在文件处理中找到平均值的总和

问题描述

所以..我需要这个项目的一些帮助。我开始学习一些关于 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()

标签: python

解决方案


这应该有效:

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()

推荐阅读