用Python从文件中读取学生成绩,并计算最高分/最低分/平均分 ...

打印 上一主题 下一主题

主题 879|帖子 879|积分 2637

兄弟们,今天咱们试试用Python从文件中读取学生成绩,并计算最高分/最低分/平均分。

涉及知识点

  • 文件读写
  • 基础语法
  • 字符串处理
  • 循环遍历
代码展示
模块
  1. import platform
  2. # 我还给大家准备了这些资料:Python视频教程、100本Python电子书、基础、爬虫、数据分析、web开发、机器学习、人工智能、面试题、Python学习路线图、问题解答!
  3. # 都放在这个扣群啦:279199867
复制代码
 
定义获取最高分、最低分及平均分函数
  1. def compute_score():
  2.     scores = []
  3.     with open("./py023.txt", encoding="utf8") as fin:
  4.         for line in fin:
  5.             line = line.strip()
  6.             fields = line.split(",")
  7.             scores.append(int(fields[-1]))
  8.     max_score = max(scores)
  9.     min_score = min(scores)
  10.     avg_score = round(sum(scores) / len(scores), 2)
  11.     return max_score, min_score, avg_score
复制代码
 
调用函数
  1. max_score, min_score, avg_score = compute_score()
  2. print("最高分:" + str(max_score) +
  3.       "\n" + "最低分:" + str(min_score) +
  4.       "\n" + "平均分:" + str(avg_score))
复制代码
 
全部代码
  1. # 导入系统包import platformprint("待到红旗满天下,马踏东京赏樱花。富士山上扬汉旗,樱花树下醉胡姬。")print("Python从文件中读取学生成绩,并计算最高分/最低分/平均分 \n")# 定义获取最高分、最低分及平均分函数def compute_score():
  2.     scores = []
  3.     with open("./py023.txt", encoding="utf8") as fin:
  4.         for line in fin:
  5.             line = line.strip()
  6.             fields = line.split(",")
  7.             scores.append(int(fields[-1]))
  8.     max_score = max(scores)
  9.     min_score = min(scores)
  10.     avg_score = round(sum(scores) / len(scores), 2)
  11.     return max_score, min_score, avg_score# 调用函数max_score, min_score, avg_score = compute_score()
  12. print("最高分:" + str(max_score) +
  13.       "\n" + "最低分:" + str(min_score) +
  14.       "\n" + "平均分:" + str(avg_score))print("Python 版本", platform.python_version())
复制代码
 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

老婆出轨

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表