前言
Python如何读取分数,计算最高/低分 与平均分?
今天这篇文章就来带你学习学习如何实现这个功能~
环境使用:
Python 3.8 解释器
Pycharm 编辑器
涉及知识点
- 文件读写
- 基础语法
- 字符串处理
- 循环遍历
代码展示
模块
import platform
定义获取最高分、最低分及平均分函数
def compute_score():
scores = []
with open("./py023.txt", encoding="utf8") as fin:
for line in fin:
line = line.strip()
fields = line.split(",")
scores.append(int(fields[-1]))
max_score = max(scores)
min_score = min(scores)
avg_score = round(sum(scores) / len(scores), 2)
return max_score, min_score, avg_score
调用函数
max_score, min_score, avg_score = compute_score()
print("最高分:" + str(max_score) +
"\n" + "最低分:" + str(min_score) +
"\n" + "平均分:" + str(avg_score))
全部代码
import platform
print("待到红旗满天下,马踏东京赏樱花。富士山上扬汉旗,樱花树下醉胡姬。")
print("Python从文件中读取学生成绩,并计算最高分/最低分/平均分 \n")
def compute_score():
scores = []
# 源码、解答、教程皆+VX:xiaoyuanllsll
with open("./py023.txt", encoding="utf8") as fin:
for line in fin:
line = line.strip()
fields = line.split(",")
scores.append(int(fields[-1]))
max_score = max(scores)
min_score = min(scores)
avg_score = round(sum(scores) / len(scores), 2)
return max_score, min_score, avg_score
max_score, min_score, avg_score = compute_score()
print("最高分:" + str(max_score) +
"\n" + "最低分:" + str(min_score) +
"\n" + "平均分:" + str(avg_score))
print("Python 版本", platform.python_version())
最后
文章分享到这里就结束啦 下一篇文章再见啦
如果有什么不懂可以留言或者私信哦 /// 也可以点击文末名片 学习交流~