Search code examples
pythonpython-3.xerror-handling

Code returns "float" object is not iterable


I'm trying to get the extra credit on an assignment and ran into an issue with the 3rd line from the bottom returning with an error! I need it to print out the assignment average grade code is below:

def print_report(students, num_of_assignments):

    # Prints Scores 
    print("\nFinal grade report:")
    for student_id, student_info in students.items():
        print(f"{student_info['Name']}'s average score was {student_info['Average']:.1f}, letter grade of {student_info['Letter_Grade']}")
    
    # Calculates and prints the average score for each student (Extra Credit)
    print("\nAssignment averages: ")
    for i in range(num_of_assignments):
        assignment_averages = sum(student_info["Scores"][i] for student_info in students.values()) / len(students)
        for i, avg_score in assignment_averages:
            print(f"The average for assignment {i} was {avg_score:.1f}, letter grade of {get_letter_grade(avg_score)}")

I know its something with the list function clashing with a dictionary but need help!


Solution

  • Change the bottom bottom portion of code to this:

    # Calculates and prints the average score for each assignment (Extra Credit)
    print("\nAssignment averages: ")
    for i in range(num_of_assignments):
        assignment_scores = [student_info["Scores"][i] for student_info in students.values()]
        avg_score = sum(assignment_scores) / len(students)
        print(f"The average for assignment {i + 1} was {avg_score:.1f}, letter grade of {get_letter_grade(avg_score)}")
    

    The issue was with how you where assigning assignment_scores. It was not wrapped in an array/list to be run in the sum function.

    When in doubt, break it out! A few more lines for better code readability is always going to be better than a short, difficult to understand program.