def AddStudent():
#Variable to control the loop
again = 'y'
#While loop that gets user input to be added to dictionary
while again.lower() == 'y':
student_key = input("What's the name of the student? ")
#Ask user for number of grades
n = int(input('How many grades do you wish to input? '))
#Empty list where grades will be saved
grades = []
#for loop to add as many grades as user wishes
for i in range(0 ,n):
grade = int(input(f'Grade {i + 1}: '))
grades.append(grade)
#Call StudentGradeBook and send values as parameters
StudentGradeBook(student_key, grades)
again = input('Do you wish to add another student? (y) ')
def StudentGradeBook(name, grade_value):
#Dictionary of the grades
grade_book = {'Tom':[90,85,82], 'Bob':[92,79,85]}
#Add the key and value to the dict
grade_book[name] = grade_value
print(grade_book)
When I add more than one name and grade list to the dict, it just replaces the third one instead of adding a 4th, 5th, etc.
This is the output:
What's the name of the student? Bill
How many grades do you wish to input? 3
Grade 1: 88
Grade 2: 88
Grade 3: 88
{'Tom': [90, 85, 82], 'Bob': [92, 79, 85], 'Bill': [88, 88, 88]}
Do you wish to add another student? (y) y
What's the name of the student? Thomas
How many grades do you wish to input? 3
Grade 1: 87
Grade 2: 88
Grade 3: 88
{'Tom': [90, 85, 82], 'Bob': [92, 79, 85], 'Thomas': [87, 88, 88]}
Do you wish to add another student? (y) n
>Solution :
I suggest that you save all the inputs in a list, then you pass the list to StudentGradeBook() :
def AddStudent():
# Variable to control the loop
again = 'y'
# Keep track of your inputs
inputs_list = []
# While loop that gets user input to be added to dictionary
while again.lower() == 'y':
student_key = input("What's the name of the student? ")
# Ask user for number of grades
n = int(input('How many grades do you wish to input? '))
# Empty list where grades will be saved
grades = []
# for loop to add as many grades as user wishes
for i in range(0, n):
grade = int(input(f'Grade {i + 1}: '))
grades.append(grade)
# Save the inputs before calling StudentGradeBook
inputs_list.append([student_key, grades])
again = input('Do you wish to add another student? (y) ')
# Call StudentGradeBook and pass the inputs as a list
StudentGradeBook(inputs_list)
def StudentGradeBook(grades):
grade_book = {'Tom': [90, 85, 82], 'Bob': [92, 79, 85]}
grade_book.update(grades)
print(grade_book)