Creating python list and displaying list items in input field

Viewed 471

Hello I'm very new to coding here (Chapter 5 in textbook) I want to input x amount of students and x amount of grades per student. eventually I will calculate the grade average per student but as of right now I am struggling with the input.

number_students = int(input("Number of Students: ")) #get number of students
number_grades = int(input ("How many grades per student: ")) #get number of grades per student
student_list = [] #create empty student list
student_grade = [] #create empty grade list
for num in range(number_students):
    student_list.append(input("Enter Student Name: ")) #create an array based on number of students
    for num in range (number_grades):
        student_grade.append(int(input("Enter grade for #enter student name here# "))) #create an array based on number of grades ```

I can't get the student name to show in the student_grade input field and secondly, is there a better way to get the grade list to correspond with the correct student rather than having a really long grade list? Maybe having each student name entry be a list then having the grade list embedded in there?

2 Answers

One way is to use a list of dictionaries:

number_students = int(input("Number of Students: "))
number_grades = int(input ("How many grades per student: "))
for num in range(number_students):
    student_name = input("Enter Student Name: ")
    student_grades = []
    for num in range(number_grades):
        student_grades.append(int(input(f"Enter {student_name}'s grade")))
    student_list.append({
                        'student': student_name,
                        'grades': student_grades
                 })

print(student_list[0]['student'])
print(student_list[0]['grades'])

You can use python dictionaries:

number_students = int(input("Number of Students: ")) #get number of students
number_grades = int(input ("How many grades per student: ")) #get number of grades per student
student_list = {} #create empty student dictionary
for num in range(number_students):
    name = input("Enter Student Name: ")
    student_list[name] = []
    for num in range(number_grades):
        grade = input(f"Enter grade for {name} ")
        student_list[name] += [grade]

Output:

Number of Students: 3
How many grades per student: 2
Enter Student Name: Johnny
Enter grade for Johnny 80
Enter grade for Johnny 92
Enter Student Name: Manny
Enter grade for Manny 78
Enter grade for Manny 59
Enter Student Name: Sarah
Enter grade for Sarah 98
Enter grade for Sarah 89
{'Johnny': ['80', '92'], 'Manny': ['78', '59'], 'Sarah': ['98', '89']}
Related