Python 如何在文件处理中求平均值之和

Python 如何在文件处理中求平均值之和,python,Python,所以..我需要一些帮助来完成这个项目。我开始学习一些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(

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

您需要在一个sperate变量中计算销售额。然后除以无天数:

ifile = open(r'`enter code here`sales.txt', 'w')
no_days = 7
total_sales = 0
for 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}")

您需要在一个sperate变量中计算销售额。然后除以无天数:

ifile = open(r'`enter code here`sales.txt', 'w')
no_days = 7
total_sales = 0
for 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}")
这应该起作用:

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()
这应该起作用:

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

将所有输入相加,然后除以计数。将变量
total
初始化为
0
,执行
total+=sales
以获得总和。欢迎使用堆栈溢出!将所有输入相加,然后除以计数。将变量
total
初始化为
0
,执行
total+=sales
以获得总和。欢迎使用堆栈溢出!非常感谢你的帮助。我还在学习python,但我已经上二年级了,所以这会对我有很大帮助。很好,学习愉快。如果我的解决方案对您有效,您是否介意接受答案。因此,我尝试使用与您完全相同的代码,但问题是ifile.write()行出现无效语法错误确保您使用的是python版本3+我使用的是python 3.8.4非常感谢您的帮助。我还在学习python,但我已经上二年级了,所以这会对我有很大帮助。很好,学习愉快。如果我的解决方案对您有效,您是否介意接受答案。因此,我尝试使用与您完全相同的代码,但问题是ifile.write()行出现无效语法错误确保您使用的是python版本3+我使用的是python 3.8.4好的,非常感谢您回答我的问题。我已经上二年级了,所以我需要一些帮助,因为我们的主题是关于文件处理的,所以让我试着使用这个代码好吧,非常感谢你回答我的问题。我已经上二年级了,所以我需要一些帮助,因为我们的主题是关于文件处理的,所以让我试着使用这段代码