Day 21: Review & Expand

Combine Week 3: Define a function that takes a dict of student grades, handles errors in input, reads from a file if exists, and returns average grade. (Concepts: functions, dicts, try/except, files)

def average_grade(grades_dict):
    try:
        total = sum(grades_dict.values())
        avg = total / len(grades_dict)
        return avg
    except (KeyError, ZeroDivisionError):
        return "Error calculating average!"

# Simulate file read (or use open in real)
student_grades = {"Alex": 85, "Bob": 92}  # From file
avg = average_grade(student_grades)
print("Average:", avg)

Day 21: Full integration! Function average_grade(grades_dict): Params dict. try: sums values (sum(grades_dict.values())), divides by length, returns avg. except catches key errors or /0 (empty dict).

Here, hardcode dict (expand to file read: open(), read(), parse). Call, print. Run: Average: 88.5. In time, add file I/O fully or more error types. Reviews all—functions compute, dicts store, try/except protects, files persist. You're building mini-apps now!

Key Concepts:

  • sum() and .values(): sum(dict.values()) totals dict values; .values() gets values only.
  • Integration of Concepts: Combining functions, dicts, error handling, and files for practical scripts.
  • len(): (Repeated from Day 3) Returns count of items (e.g., dict keys).

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top