This page contains exercise answers and teaching guidance for
Step 8 — Save High Score.
Not linked from the student pages.
Students: please go back and try the activities first.
open() with modes "r" and "w" to read and write text filesFileNotFoundError with try / exceptSCORE_FILE = "high_score.txt"
# ── Load high score from file ──
try:
with open(SCORE_FILE, "r") as f:
high_score = int(f.read().strip()) # strip() removes newline
except FileNotFoundError:
high_score = 0 # first time running — file doesn't exist yet
except ValueError:
high_score = 0 # file exists but content is not an integer
# ── Save high score to file ──
def save_score(score, high_score):
if score > high_score:
high_score = score
with open(SCORE_FILE, "w") as f:
f.write(str(high_score))
return high_score
# ── f-string formatting ──
name = "Nurul"
score = 42
print(f"Player: {name} — Score: {score:04d}") # → "Player: Nurul — Score: 0042"
pygame.display.set_caption(f"Snake — Score: {score} Best: {high_score}")
# ── Leaderboard (dictionary) ──
leaderboard = {} # {"PlayerName": best_score}
def update_leaderboard(name, score):
if name not in leaderboard or score > leaderboard[name]:
leaderboard[name] = score
with open(path, mode) as f: — the with statement ensures the file is closed even if an error occurs. "r" = read, "w" = write (overwrites), "a" = append.try / except — try runs code that might fail; except ExceptionType: catches a specific error type. Always catch the most specific exception you can.FileNotFoundError — raised when open() is called on a file that doesn't exist. Common in file I/O — always handle it..strip() — removes leading/trailing whitespace including
(newline). A file read with f.read() often ends with a newline.f"..." — embed expressions directly in strings with {variable}. {score:04d} formats as a 4-digit integer with leading zeros.Students complete two function skeletons: load_high_score() and save_high_score(score). Six blanks in total.
| Blank | Correct answer | Why |
|---|---|---|
Blank 1 — file mode in load_high_score |
"r" |
Reading an existing file requires read mode. |
Blank 2 — wrapper around f.read().strip() |
int |
The file stores the score as text; int() converts it to a number for comparison. |
Blank 3 — return value in except FileNotFoundError |
0 |
First run: no file yet, so the default high score is 0. |
Blank 4 — function called at start of save_high_score |
load_high_score |
Must fetch the current best before deciding whether to overwrite it. |
| Blank 5 — comparison operator | > |
Only save when the new score beats the previous best. |
Blank 6 — file mode in save_high_score |
"w" |
Write mode creates or overwrites the file with the new best score. |
SCORE_FILE = "highscore.txt"
def load_high_score():
try:
with open(SCORE_FILE, "r") as f: # blank 1: "r"
return int(f.read().strip()) # blank 2: int
except FileNotFoundError:
return 0 # blank 3: 0
def save_high_score(score):
best = load_high_score() # blank 4: load_high_score
if score > best: # blank 5: >
with open(SCORE_FILE, "w") as f: # blank 6: "w"
f.write(str(score))
| Bug | Buggy line | Fixed line | Explanation |
|---|---|---|---|
| 1 | with open(SCORE_FILE, "a") as f: |
with open(SCORE_FILE, "r") as f: |
Mode "a" (append) opens for writing only, not reading. Used inside load_high_score it returns nothing readable. Must be "r". |
| 2 | return f.read().strip() |
return int(f.read().strip()) |
Without int(), the function returns a string like '42'. Comparing a string with > to an integer causes a TypeError. |
| 3 | if score < best: |
if score > best: |
The logic is inverted: using < saves the score only when it is worse than the record. Must use > to overwrite only when beaten. |
Students add display_high_score() using an f-string and reset_high_score() that writes 0 back to the file.
def display_high_score():
best = load_high_score()
print(f"👑 High Score: {best}")
def reset_high_score():
with open(SCORE_FILE, "w") as f:
f.write("0")
print("High score has been reset to 0.")
Accept any f-string that includes the score value. Accept deleting the file via os.remove(SCORE_FILE) as an alternative to writing 0.
Students build a ScoreManager that wraps all file operations and run a demo loop over [12, 45, 30, 67, 55].
class ScoreManager:
def __init__(self, filename="highscore.txt"):
self.filename = filename
def load(self):
try:
with open(self.filename, "r") as f:
return int(f.read().strip())
except FileNotFoundError:
return 0
def save(self, score):
best = self.load()
if score > best:
with open(self.filename, "w") as f:
f.write(str(score))
print(f"👑 New high score: {score}!")
else:
print(f"Score {score} did not beat the record ({best}).")
def display(self):
print(f"Current high score: {self.load()}")
def reset(self):
with open(self.filename, "w") as f:
f.write("0")
print("High score reset.")
# Demo
sm = ScoreManager()
sm.reset()
for score in [12, 45, 30, 67, 55]:
print(f"\nGame ended with score: {score}")
sm.save(score)
sm.display()
Expected output: new high score at 12, 45, 67. Scores 30 and 55 do not beat record. Final display shows 67.
| Prompt | Key ideas a strong answer contains |
|---|---|
1. Why is except FileNotFoundError safer than bare except:? |
Bare except: silently catches everything — including KeyboardInterrupt and SystemExit — hiding real bugs. A specific exception catches only the expected failure and lets unexpected errors surface. |
2. What does the with statement guarantee? |
The file is automatically closed when the block exits, even if an error occurs inside. Without it, forgetting f.close() can cause data loss or file locks if the program crashes mid-write. |
3. Why is int(f.read().strip()) needed — not just f.read()? |
Files store everything as text. f.read() returns a string like '42
'. .strip() removes the trailing newline; int() converts the string to a number so comparisons with > work correctly. |
4. When would you choose "a" (append) instead of "w" (write)? |
Use "a" when you want to add new lines without erasing existing content — a log file, for example. Use "w" when you want to replace the entire file, such as updating the single best score. |
| 5. How would you store the top 3 high scores instead of just one? | Read the file into a list, append the new score, sort descending, keep only the top 3, then write all three back — one per line. Or use JSON: json.dump([...], f) and json.load(f). |
| What they did | What they see | What to say |
|---|---|---|
open(file, "w") to read |
File is silently overwritten with nothing — old high score lost | ""w" is write mode — it DESTROYS existing content. Use "r" to read." |
No .strip() on f.read() |
ValueError — the integer string has a trailing newline |
"Files often end with
. .strip() removes it. Always strip before converting to int." |
except: (bare) |
Catches everything including KeyboardInterrupt and SystemExit |
"Always specify the exception: except FileNotFoundError:. Bare except: is a bad habit that hides real errors." |
Forgot str() in f.write(score) |
TypeError: write() argument must be str, not int |
"f.write() takes a string. Convert first: f.write(str(high_score)) or use an f-string." |
f"Score: " + score |
TypeError: can only concatenate str (not "int") to str |
"Inside an f-string, put the variable in braces: f"Score: {score}". Don't use + with f"..." — it defeats the purpose." |
"What happens to your high score if the power goes out?" For students who've played arcade games, this is intuitive. File I/O is how software remembers things beyond a single session.
Before explaining it, ask students to delete high_score.txt (or pretend they're running for the first time) and run the code without the try/except. They'll see the crash. Now add try/except and show it works. Failure first, solution second — the most memorable teaching sequence.
Emphasise that with open(...) as f: automatically closes the file. Without it, forgetting f.close() can cause data loss or file locks. "It's like a responsible borrower — it returns the book before walking out the door."
Some students may have seen "Score: %d" % score in older tutorials. f-strings are the modern, readable standard — steer students toward them.
Ask: "What other game data might you want to persist across sessions? Player settings? Unlocked levels? Items? What file format would you use?" This opens the door to JSON and databases.
These 5 questions appear in the activity page after Tier 4 (post-calibration gate). Pass mark is 4 of 5 (80%). Students who fail may retry; the system records attempts and final score in Google Sheets.
| # | Question (displayed to student) | Correct option (0-indexed) | Correct Answer |
|---|---|---|---|
| Q1 | Which file mode is used to read an existing file? | 0 | ✓ "r" |
| Q2 | What does except FileNotFoundError: do? |
1 | ✓ Handles the case where the file does not exist yet, so the program does not crash on first run |
| Q3 | Why use with open(...) as f: instead of just open()? |
1 | ✓ It automatically closes the file when the block exits, even if an error occurs |
| Q4 | What does int(f.read().strip()) do? |
1 | ✓ Reads the file content as text, removes surrounding whitespace, then converts the result to an integer |
| Q5 | Why does save_high_score(score) call load_high_score() first? |
1 | ✓ To retrieve the previous best so it can compare and only overwrite when the new score is higher |
Recorded in Google Sheet (Act_8 tab):
concept_q1_ans–concept_q5_ans (student's 0-based answer index),
concept_q1_cor–concept_q5_cor (1 = correct, 0 = wrong),
concept_score_pct, concept_passed (1 = pass, 0 = fail),
concept_attempts (retry count).
Every submission to this step writes one row to the Act_8 tab in the research spreadsheet. All 13 tabs (Student_Reg, Pre_Test, Post_Test, Act_1–Act_10) share the same student identity columns.
| Column | Description |
|---|---|
| STUDENT IDENTITY (10 fields) | |
matric | Matric / student ID |
name | Full name |
gender | Gender (Female / Male / Other) |
age | Age in years |
mykid | MyKid / IC number |
home_state | Home state in Malaysia |
class | Class or cohort code |
school_code | School or programme code |
phone | Phone number |
email | Email address |
| SUBMISSION | |
step | Step number (8) |
submitted_iso | KL timestamp (UTC+8, ISO 8601) |
| PRE-CALIBRATION | |
cal_confidence | Self-confidence before activity (1–5 scale) |
cal_predicted | Predicted score before activity (%) |
cal_reflection | Free-text: what will be hard? |
| ACTIVITY TIERS | |
t1_score_pct | Tier 1 Fill-in-Blanks score (%) |
t2_attempts | Tier 2 Debug — number of attempts |
refl2_text | Tier 2 reflection free text |
t3_attempts | Tier 3 Complete-Code attempts |
t4_attempts | Tier 4 New Task attempts |
| CONCEPT CHECK | |
concept_q1–concept_q5 | Student answer index (0-based) per question |
concept_score_pct | Percentage correct (0–100) |
concept_passed | 1 = passed (≥80%), 0 = failed |
concept_attempts | Total retries |
| REFLECTIVE JOURNAL | |
jr1–jr5 | Journal prompts 1–5 free-text responses |
| POST-CALIBRATION | |
post_confidence | Confidence rating after activity (1–5) |
post_actual | Self-reported actual score (%) |
post_r1 | Reflection: how accurate was the prediction? |
post_r2 | Reflection: what would you do differently? |
calibration_index | post_actual − cal_predicted (negative = overconfident) |