You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python读取文件计算数值总和、平均值、最小值、最大值功能求助

Python数值统计程序修改方案

核心修改逻辑如下:

  • 调整readFile函数,新增最小/最大值统计逻辑,返回值新增最小、最大值两个结果
  • 调整main函数的参数传递逻辑,接收readFile返回的所有统计值
  • 调整display函数,新增平均值计算逻辑,补充最小、最大值的打印,新增空文件判断避免除零错误

修改后的完整代码:

def main ():
     contents=''
     
     try:
        infile = openFile()

        count, total_sum, min_val, max_val = readFile(infile)

        closeFile(infile)

        display(count, total_sum, min_val, max_val)

     except IOError:
          print('Error, input file not opened properly')

     except ValueError:
          print('Error, data within the file is corrupt')


def openFile():
     infile=open('numbers.txt', 'r')
     return infile


def readFile(inf):
     count = 0
     total_sum = 0
     # 初始化最小/最大值为极值,方便后续比较更新
     min_val = float('inf')
     max_val = float('-inf')

     line = inf.readline()

     while line != '':
          number = int(line)
          total_sum += number
          # 更新最小、最大值
          if number < min_val:
              min_val = number
          if number > max_val:
              max_val = number
          count += 1
          line = inf.readline()

     return count, total_sum, min_val, max_val          

          
def closeFile(inF):
     inF.close()

def display(count, total, min_val, max_val):
     print('count = ', count)
     print('Sum = ', total)
     # 空文件判断,避免除零报错
     if count == 0:
         print('No valid numbers in the file')
         return
     average = total / count
     print('Average = ', average)
     print('Min = ', min_val)
     print('Max = ', max_val)


main()

测试效果(输入文件数值为14、22、-99):

count =  3
Sum =  -63
Average =  -21.0
Min =  -99
Max =  22

内容的提问来源于stack exchange,提问作者Jaxon Nessmith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 04:45:00