Save Stats on Exit
Exit

Save Stats on Exit

Define save_stats and call it when the player quits so stats survive the session

💻

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

Right now, STATS tracks your performance within a session — but the moment you quit, it resets. Next time you run the quiz, Games played starts at 0 again.

The fix is the reverse of what you did with load_questions: when the player quits, write STATS to a file.

def save_stats():
    with open(STATS_FILE, "w") as f:
        json.dump(STATS, f, indent=2)

json.dump converts STATS to JSON text and writes it to the file. The "w" mode creates the file if it does not exist, or overwrites it if it does — which is what you want, since you are replacing the old stats with the updated ones. indent=2 formats the output with two-space indentation so the file is readable if you open it.

The right time to call save_stats is right before the break that ends the game. At that point, STATS has already been updated with the last round's results.

Instructions

Add save_stats and call it when the player quits.

  1. Below QUESTIONS_FILE = "questions.json", add STATS_FILE = "stats.json" — keeping all file path constants together.
  2. Before run_quiz, define a function called save_stats with no parameters. Inside, open STATS_FILE in write mode ("w") using with open(...) as f:, then call json.dump(STATS, f, indent=2).
  3. In the main loop, find the line if again != "y":. Add save_stats() on the line before break — so stats are written to disk every time the player quits.