Oct-18-2020, 01:16 PM
Hi there,
I have just been going through a basic sample bit of code designed to teach about tuples and dictionaries.
For completeness, please see the full bit of code below first of all. But not, that it is only a snippet of the code that I want to focus on. The code is an example of taking a series of students' names and their grades and then calculating the average grade for each student.
Would someone be able to explain what I am misunderstanding here?
I have just been going through a basic sample bit of code designed to teach about tuples and dictionaries.
For completeness, please see the full bit of code below first of all. But not, that it is only a snippet of the code that I want to focus on. The code is an example of taking a series of students' names and their grades and then calculating the average grade for each student.
school_class = {} while True: name = input("Enter the student's name (or type exit to stop): ") if name == 'exit': break score = int(input("Enter the student's score (0-10): ")) if name in school_class: school_class[name] += (score,) else: school_class[name] = (score,) print(school_class) for name in sorted(school_class.keys()): adding = 0 counter = 0 for score in school_class[name]: adding += score counter += 1 print(name, ":", adding / counter)So the snippet I want to focus on is:
if name in school_class: school_class[name] += (score,) else: school_class[name] = (score,)What is confusing me about this snippet is that the line
school_class[name] += (score,)seems to be appending scores onto an already existing tuple. But I thought tuples were immutable and as such you would not be able to modify an already existing tuple.
Would someone be able to explain what I am misunderstanding here?