How can I use each() function in the context of Python?
Recently I have been assigned a task in which I need to implement the for each() function of Python programming language in one of the lists which include the respective subjects and grades of students. How can I implement this particular function to calculate the average grade for each student?
Certainly here is the solution given by using foreach in Python for your particular scenario of calculating the average grades of each student:-
# Sample student data with subjects and grades
Student_data = {
‘Alice’: [80, 75, 90], # Grades for Alice in different subjects
‘Bob’: [85, 92, 88], # Grades for Bob in different subjects
# Add more students if needed
}
# Calculate average grades for each student
For students, grades in student_data.items():
Average_grade = sum(grades) / len(grades)
Print(f”{student}’s average grade is: {average_grade}”)
Explanation:-
“student_data” is the dictionary where you get the keys that represent the name of each student. Thus, each key represents the name of the Student.
The for each() function iterates through each- key-value pair in the “student_data”.
Here inside the loop of Python, the function calculates the average grade of students by using functions like “sum(grades)” and “len(grades)”. The sum(grades) is used for adding the grades of each student while len(grades) is used here to divide the number of grades.