Python计算平均成绩并筛选高于平均分的成绩

这篇文章将教你如何使用Python编写一个简单的程序,用于计算一组成绩的平均值,并将高于平均分的成绩筛选出来并输出。

以下是完整的代码示例:pythonscores = input('please enter the scores in form of list: ')scores = eval(scores) # 将输入的字符串转换为列表

average_score = sum(scores) / len(scores)print('the average score is: {:.1f}'.format(average_score))

higher_scores = [score for score in scores if score > average_score]print('the score list higher than average score:', higher_scores)

代码解释:

  1. 获取用户输入: - scores = input('please enter the scores in form of list: '):提示用户输入成绩列表,并将输入存储在scores变量中。2. 将字符串转换为列表: - scores = eval(scores):使用eval()函数将用户输入的字符串转换为Python列表。3. 计算平均分: - average_score = sum(scores) / len(scores):使用sum()函数计算成绩总和,使用len()函数获取成绩数量,然后将总和除以数量得到平均分。4. 筛选高于平均分的成绩: - higher_scores = [score for score in scores if score > average_score]:使用列表推导式筛选出高于平均分的成绩,并将结果存储在higher_scores列表中。5. 输出结果: - print('the average score is: {:.1f}'.format(average_score)):输出平均分,保留一位小数。 - print('the score list higher than average score:', higher_scores):输出高于平均分的成绩列表。

如何运行程序:

  1. 将代码保存为.py文件,例如calculate_scores.py。2. 在命令行中使用python calculate_scores.py命令运行程序。3. 按照提示输入成绩列表,例如[99, 80, 95, 89, 96]。4. 程序将输出平均分和高于平均分的成绩列表。

希望这篇文章能帮助你理解如何使用Python计算平均成绩并筛选高于平均分的成绩。

Python计算平均成绩并筛选高于平均分的成绩

原文地址: https://www.cveoy.top/t/topic/b8b1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录