首页 > 解决方案 > 如何从 python 中的用户 2 值读取并找到最高 GPA?

问题描述

如何编写 python 代码以在一行中从用户读取学生姓名和 GPA,但是如果用户输入类似 (off) 的单词,程序将停止.. 我想使用 while 循环并计算并打印最高 GPA 和学生姓名?

2 个值 = 第一个 int .. 第二个字符串。喜欢= GPA ...名称

标签: pythonloopswhile-loopintgpa

解决方案


不确定您想对结果做什么或如何存储它们,但这应该让您开始使用您需要的东西。

from collections import defaultdict

def get_mean_grades():
    students = defaultdict(list)
    while True:
        data = input('Enter your GPA followed by your name: ')
        if data.upper() == 'STOP':
            break
        else:
            gpa, name = data.split(' ', 1)
            students[name].append(float(gpa))
    print()
    for student, grades in students.items():
        average = sum(grades) / len(grades)
        print(f"{student} has an average grade of {average}")

Enter your GPA followed by your name: 4.3 Tom Morris
Enter your GPA followed by your name: 2.2 Fred York
Enter your GPA followed by your name: 4.8 Tom Morris
Enter your GPA followed by your name: 3.3 Fred York
Enter your GPA followed by your name: STOP

Tom Morris has an average grade of 4.55
Fred York has an average grade of 2.75

推荐阅读