How to read from user 2 values in python and find the highest GPA?

826 views Asked by At

How do I write a python code to read from user the Student Name and GPA in one line, but if user enter a word like (off) the program stops .. I want to use while loop and Calculate and print the highest GPA and student name?

2 values = First int .. Second String. like = GPA ... name

2

There are 2 answers

4
Kuldeep Singh Sidhu On
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

0
gold_cy On

Not sure what you want to do with the results or how you want to store them but this should get you started with what you need.

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