python 统计学生的课程成绩 课程名称和成绩用空格分隔,每门课程一行,遇空行按enter键结束录入。按要求输入结束后得出得分最高的课程名称及成绩,得分最低的课程名称及成绩,以及平均分(保留2位小数)))
时间: 2024-02-13 11:05:35 浏览: 29
以下是一个实现上述要求的 Python 代码示例:
```python
scores = []
while True:
score = input("请输入课程名称和成绩(用空格分隔),每门课程一行,遇空行按enter键结束录入:")
if not score:
break
scores.append(score.split())
# 计算平均分
total_score = 0
for s in scores:
total_score += float(s[1])
avg_score = total_score / len(scores)
# 查找最高分和最低分
highest_score = float(scores[0][1])
highest_course = scores[0][0]
lowest_score = float(scores[0][1])
lowest_course = scores[0][0]
for s in scores:
score = float(s[1])
if score > highest_score:
highest_score = score
highest_course = s[0]
if score < lowest_score:
lowest_score = score
lowest_course = s[0]
# 输出结果
print("得分最高的课程是:{},成绩为:{}".format(highest_course, highest_score))
print("得分最低的课程是:{},成绩为:{}".format(lowest_course, lowest_score))
print("平均分为:{:.2f}".format(avg_score))
```
代码中首先通过一个循环来读取用户输入的课程成绩,并将其存储在一个列表中。接着,通过遍历列表来计算平均分,查找最高分和最低分。最后,输出结果。
需要注意的是,代码中假设用户输入的每行都是合法的,并且课程名称和成绩之间只有一个空格。在实际应用中,可能需要根据实际情况进行相应的修改。