我如何写一个python代码,从用户中读取学生姓名和GPA在一行,但如果用户输入一个词,如(关闭)程序停止......我想使用while循环和计算和打印最高的GPA和学生姓名?
2 values = 第一个 int ... 第二个 String.like = GPA ... name
不知道你想用结果做什么,也不知道你想如何存储它们,但这应该能让你开始做你需要的事情。
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
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'}]