I assume the dict structure is as follows:
student_marks={'s1':10, 's2':9,...}
or
students_marks={'s1':'10', 's2':'9',...}
or a mix of both, in that case, you should be consistent with the type you're using as a value in a dictionary as much as you can, not that python would care it'll just throw TypeError at you, but to save yourself from possible headaches.
The problem you're getting may be caused by:
total_marks
isn't an integer and the dictionary values are integers, so you should make sure to initialize total_marks
at the beginning of your code.
The opposite case, total_marks
is an integer but, a value (or several values) in the dict are strings. You should add a line in the for loop that converts from string to integer, and make sure that the string is is a numerical string before the conversion (you can't convert the string 'a' into an integer) by either using assert or a try/except.
The code can be rewritten in a more, convenient way to catch some of the errors as follows:
students_marks={'a':10, 'b':9, 'c':5,...}
total_marks=0
#this loop iterates over the keys(in this case the students names) in the dictionary
for name in students_marks.keys():
try:
total_marks+= int(student_marks[name])
#alternatively
#total_marks+= int(student_marks.get(name,0))
except:
#this line will print out the incorrect entry in the dictionary.
print('Student {} marks are incorrect, {}'.format(name, student_marks[name]))
average_marks=total_marks/len(students_marks)
If the dictionary values are all correct, you can go:
total_marks=sum(student_marks.values())
number_of_students=len(students_marks)
average_marks=total_marks/number_of_students
You can also cram the previous code in a single line, depends on what do you need from your code.