Load Stats at Startup
Exit

Load Stats at Startup

Define load_stats to read the saved stats file and restore the player's history

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

save_stats writes the data. Now you need to read it back at startup so the player's history is restored.

There is one difference from load_questions: questions.json was already there when you wrote load_questions — you provided it. stats.json only exists after the first time the player quits. If you call open("stats.json", "r") before that file has been created, Python raises a FileNotFoundError and the program crashes.

You have already seen try/except in ask_question — it catches ValueError when the player types non-numeric input. The same pattern handles a missing file:

def load_stats():
    try:
        with open(STATS_FILE, "r") as f:
            return json.load(f)
    except FileNotFoundError:
        return {
            "games": 0,
            "best_score": 0,
            "best_total": 0,
            "total_correct": 0,
            "total_questions": 0,
        }

If the file exists, the try block succeeds and returns the saved stats. If it does not exist yet, FileNotFoundError is raised and the except block returns the default empty stats instead. Either way, STATS ends up as a valid dict.

Instructions

Define load_stats and use it to initialize STATS.

  1. Below load_questions, define a function called load_stats with no parameters. Inside:
    • Add a try: block. Inside it, open STATS_FILE in read mode ("r") using with open(...) as f: and return json.load(f).
    • Add an except FileNotFoundError: block. Inside it, return a dict with all five keys set to 0: "games", "best_score", "best_total", "total_correct", "total_questions".
  2. Replace STATS = { ... } (the entire dict literal below) with STATS = load_stats().