w3resource

Python NamedTuple function: Calculate average grade


6. Student Average Grade

Write a Python function that takes a Student named tuple as an argument and calculates the average grade.

Sample Solution:

Code:

from collections import namedtuple

# Define a NamedTuple named 'Student' with fields 'name', 'age', and 'marks'
Student = namedtuple("Student", ["name", "age", "marks"])

def calculate_average_grade(student):
    total_marks = sum(student.marks)
    average_grade = total_marks / len(student.marks)
    return average_grade

# Create an instance of the Student NamedTuple
student1 = Student(name="Ain Ruth", age=22, marks=[89, 92, 75, 90, 86])

# Calculate and print the average grade for the student
average_grade = calculate_average_grade(student1)
print("Average Grade:", average_grade)

Output:

Average Grade: 86.4

In the exercise above, we declare a "Student" NamedTuple with the fields 'name', 'age', and 'marks'. The "calculate_average_grade()" function takes a "Student" NamedTuple as input, calculates the average grade from the 'marks' field, and returns it. Next, we create an instance of the "Student" NamedTuple and calculate and print the average grade.

Flowchart:

Flowchart: Python NamedTuple function: Calculate average grade.

For more Practice: Solve these Related Problems:

  • Write a Python function that takes a `Student` NamedTuple with a list of marks and returns the average mark, handling empty marks lists by returning None.
  • Write a Python program to calculate the average grade of each student in a list of `Student` NamedTuples and print the names of students with an average above a given value.
  • Write a Python script to compute the overall average mark for a class using a list of `Student` NamedTuples and then print the result.
  • Write a Python function to compare two `Student` NamedTuples by their average marks and return the student with the higher average.

Python Code Editor :

Previous: Python NamedTuple function example: Get item information.
Next: Python NamedTuple example: Circle attributes.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.