pythonintermediate10 minutes

Refactor Nested Loops and Conditionals for Student Grade Processing

Improve the readability and efficiency of a Python function that processes student grades to calculate averages and determine pass/fail status.

Challenge prompt

You are given a Python function that processes a list of student dictionaries containing their names and grades across subjects. The function calculates the average grade for each student and assigns a 'passed' or 'failed' status based on a threshold of 60. However, the current implementation uses nested loops and multiple conditionals making it hard to maintain and less efficient. Refactor the function to improve code clarity, remove redundant checks, and use Pythonic structures such as list comprehensions and helper functions without changing its behavior.

Guidance

  • Avoid nested loops by utilizing built-in functions like sum() and len() to calculate averages.
  • Use list comprehensions or map functions to simplify list manipulation.
  • Extract repetitive logic into helper functions to enhance readability.

Hints

  • Consider calculating the average grade with a single expression rather than nested loops.
  • Use Python's ternary operator to assign the pass/fail status concisely.

Starter code

def process_student_grades(students):
    results = []
    for student in students:
        total = 0
        count = 0
        for subject, grade in student['grades'].items():
            if grade is not None:
                total += grade
                count += 1
        if count > 0:
            average = total / count
        else:
            average = 0
        if average >= 60:
            status = 'passed'
        else:
            status = 'failed'
        results.append({'name': student['name'], 'average': average, 'status': status})
    return results

Expected output

[ {'name': 'Alice', 'average': 75.0, 'status': 'passed'}, {'name': 'Bob', 'average': 58.75, 'status': 'failed'}, {'name': 'Charlie', 'average': 91.0, 'status': 'passed'} ]

Core concepts

refactoringlist comprehensionshelper functionsconditional expressions

Challenge a Friend

Send this duel to someone else and see if they can solve it.