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.
- Below
QUESTIONS_FILE = "questions.json", addSTATS_FILE = "stats.json"— keeping all file path constants together. - Before
run_quiz, define a function calledsave_statswith no parameters. Inside, openSTATS_FILEin write mode ("w") usingwith open(...) as f:, then calljson.dump(STATS, f, indent=2). - In the main loop, find the line
if again != "y":. Addsave_stats()on the line beforebreak— so stats are written to disk every time the player quits.
import json
QUESTIONS_FILE = "questions.json"
# Step 1: STATS_FILE = "stats.json"
STATS = {
"games": 0,
"best_score": 0,
"best_total": 0,
"total_correct": 0,
"total_questions": 0,
}
def load_questions():
with open(QUESTIONS_FILE, "r") as f:
return json.load(f)
QUESTIONS = load_questions()
def ask_question(q):
print(q["text"])
print()
print(f" 1) {q['options'][0]}")
print(f" 2) {q['options'][1]}")
print(f" 3) {q['options'][2]}")
print(f" 4) {q['options'][3]}")
print()
while True:
answer_text = input("Your answer (1-4): ")
try:
answer = int(answer_text)
except ValueError:
print("Please enter 1, 2, 3, or 4.")
continue
if answer < 1 or answer > 4:
print("Please enter 1, 2, 3, or 4.")
continue
break
is_correct = answer == q["correct"]
print()
print(f"You answered: {answer}")
if is_correct:
print("Correct!")
else:
print(f"Wrong! The correct answer was option {q['correct']}.")
return is_correct
def show_results(score, total):
print(f"Score: {score}/{total}")
if score == total:
print("Perfect score!")
elif score >= 2:
print("Great job!")
elif score >= 1:
print("Not bad!")
else:
print("Keep practicing!")
def show_stats():
if STATS["games"] == 0:
print("No games played yet.")
return
print(f"Games played: {STATS['games']}")
print(f"Best round: {STATS['best_score']}/{STATS['best_total']}")
print(f"Total correct: {STATS['total_correct']} out of {STATS['total_questions']}")
# Step 2: define save_stats()
def run_quiz(questions=QUESTIONS, num=None):
if num is None:
num = len(questions)
score = 0
streak = 0
questions_for_round = questions[:num]
total = len(questions_for_round)
print(f"=== Python Quiz ({total} questions) ===")
print()
for q in questions_for_round:
result = ask_question(q)
if result:
score = score + 1
streak = streak + 1
if streak >= 3:
print(f" Hot streak! ({streak} in a row)")
else:
streak = 0
show_results(score, total)
return score, total
while True:
show_stats()
print()
categories = sorted(set(q["category"] for q in QUESTIONS))
print("Categories: " + ", ".join(categories))
category = input("Category (enter for all): ").strip()
if category:
pool = [q for q in QUESTIONS if q["category"] == category]
if not pool:
print("Category not found. Playing all.")
pool = QUESTIONS
else:
pool = QUESTIONS
try:
num_input = input(f"How many questions? (1-{len(pool)}, enter for all): ").strip()
if num_input:
num = int(num_input)
else:
num = len(pool)
except ValueError:
num = len(pool)
print()
score, total = run_quiz(pool, num)
STATS["games"] = STATS["games"] + 1
STATS["total_correct"] = STATS["total_correct"] + score
STATS["total_questions"] = STATS["total_questions"] + total
if score > STATS["best_score"]:
STATS["best_score"] = score
STATS["best_total"] = total
print()
again = input("Play again? (y/n): ")
if again != "y":
# Step 3: call save_stats() here, then break
break
print("Thanks for playing!")
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding