如何在python中从用户中读取2个值并找到最高的GPA?

问题描述 投票:-1回答:1

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

2 values = 第一个 int ... 第二个 String.like = GPA ... name

python loops while-loop int gpa
1个回答
-1
投票

不知道你想用结果做什么,也不知道你想如何存储它们,但这应该能让你开始做你需要的事情。

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

-2
投票
data = []
while True:
    inp = [i for i in input("Please enter your name followed by your GPA: ").strip().split()]
    if (len(inp)==1 or inp[0] == 'off'): break
    data.append({'Name':(' '.join([str(i) for i in inp[:-1]])) , 'GPA':float(inp[-1])})

# print(data)
Please enter your name followed by your GPA: Kuldeep Singh 2.1
Please enter your name followed by your GPA: Kuldeep 3.1
Please enter your name followed by your GPA: Peter Smith 4.0
Please enter your name followed by your GPA: off
[{'GPA': 2.1, 'Name': 'Kuldeep Singh'},
 {'GPA': 3.1, 'Name': 'Kuldeep'},
 {'GPA': 4.0, 'Name': 'Peter Smith'}]

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.