Year 9 · Y9.3 Python Programming · Lesson 3
Stretch tasks Files and building a real program
Quiz Challenge
A quiz game against four computer players, then short and long written answers.
- Quiz Blitz12 questions against the clock
- Quick Fire4 short answers
- Big Think2 long answers
About 20 minutes
This or That
Pixel the cat asks 8 questions. Each has two answers: pick the right one.
- Two answers to every question
- A fish treat for every right answer
- Streaks win Pixel shades, then a party hat
About 4 minutes
Memory Match
Flip the cards two at a time to match each code card to its meaning card.
- 12 cards: each code has a meaning
- One peek at every card
- Combo points for pairs found in a row
6 pairs, about 4 minutes
The games need JavaScript. Every question is below, with the answers at the end.
Read the lesson: Files and building a real program
Files and building a real program: the questions
Quiz Challenge, round 1: Quiz Blitz
Which mode adds to the end of a file without erasing it?
"w""r""x""a"
Opening a file in "w" mode keeps its old contents and adds new lines at the end.
- True
- False
Why use with open(...) as file: ?
- The file is closed automatically, even if an error happens
- It makes the file smaller
- It encrypts the file
- It is the only way to read a file
What is printed?
line = "Aisha,82\n" name, score = line.strip().split(",") print(score + score)- 164
- 82
- An error
- 8282
What is printed?
line = "Ben,64\n" name, score = line.strip().split(",") print(int(score) + 1)A program opens scores.txt to read it, but the file does not exist. Which error happens?
- IndexError
- NameError
- ZeroDivisionError
- FileNotFoundError
In the lesson's program, what does try ... except FileNotFoundError do?
- Stops the program immediately
- Starts with no scores instead of crashing when there is no file yet
- Deletes the old file
- Creates a new folder
Put these in the order the score program does them.
Number these 1 to 4.
- Add the new score
- Show the top score
- Save the scores back to the file
- Load the scores from the file
Which TWO are true about .strip()?
Tick 2.
- It deletes the file
- It removes the newline at the end of a line
- It removes spaces from the start and end
- It splits the line at commas
- It turns text into a number
What is printed?
scores = {"Ali": 70, "Bea": 85, "Cal": 60} best = max(scores, key=scores.get) print(best)- 85
- Ali
- Cal
- Bea
Data in a variable is lost when the program ends, but data saved in a file is not.
- True
- False
How many lines are in log.txt after this runs?
with open("log.txt", "w") as f: f.write("one\n") with open("log.txt", "a") as f: f.write("two\n") with open("log.txt", "w") as f: f.write("three\n")
Quiz Challenge, round 2: Quick Fire
Explain the difference between opening a file in "w" mode and in "a" mode. [2 marks]
Why do programs save data to files? [2 marks]
What is printed, and why? [2 marks]
data = "10,20" a, b = data.split(",") print(a + b)Why should a program handle FileNotFoundError when it loads saved data? [2 marks]
Quiz Challenge, round 3: Big Think
Explain what this code does, one line at a time. [4 marks]
with open("scores.txt", "r") as file: for line in file: name, score = line.strip().split(",") print(name, "scored", score)Plan a high-score program for a game that remembers scores between sessions. Explain the subroutines, the data structure and the file handling you would use. [6 marks]
This or That: tick the right answer
Which mode empties a file before writing to it?
"a""w"
Which mode opens a file only to read it?
"r""w"
What is printed?
line = "Ben,64\n" name, score = line.strip().split(",") print(score)- 64
- Ben
Why does a score read from a file need int() before you add to it?
- Everything read from a text file is text
- Files store every number as a decimal
Why split a program into four small subroutines rather than one long block?
- Each job can be read, tested and fixed alone
- The program then needs fewer variables
What is printed?
print("a,b,c".split(","))['a', 'b', 'c']a b c
A program opens a file in "w" mode twice, writing 3 lines each time. How many lines are left?
- 3
- 6
What is printed?
print(" hi\n".strip())hi, with no spaceshi, with two spaces
Memory Match: match each code to its meaning
| Code | Meaning |
|---|---|
A open("f.txt", "r") | 1 Cuts a string into a list at each comma |
B open("f.txt", "w") | 2 Opens a file to add to the end |
C open("f.txt", "a") | 3 Removes spaces and newlines from both ends |
D .strip() | 4 Opens a file and empties it first |
E .split(",") | 5 Turns a number into text |
F str(77) | 6 Opens a file to read it |
Answers
Round 1: Quiz Blitz
"a"a is append. w is write, which erases the file first.- False Write mode wipes the file the moment it is opened. Use append mode to add to it.
- The file is closed automatically, even if an error happens with guarantees the file is closed when the block ends, error or not.
- 8282 Everything read from a text file is a string. "82" + "82" joins them: 8282. Use int() to do maths.
- 65 int() turns the text "64" into the number 64, so 64 + 1 = 65.
- FileNotFoundError Reading a missing file raises FileNotFoundError, which try and except can catch.
- Starts with no scores instead of crashing when there is no file yet The first time the program runs there is no file. Catching the error lets it start fresh.
- Load the scores from the file → Add the new score → Show the top score → Save the scores back to the file Load, change, show, save. Saving last means the new score is kept for next time.
- It removes the newline at the end of a line; It removes spaces from the start and end strip tidies the ends of a string. split is what breaks it apart.
- Bea max with key=scores.get compares the values but returns the key with the biggest one.
- True Variables live in memory. Files live in storage, so they are still there next time.
- 1 The last open uses w, which wipes the file before writing three. Only that line is left.
Round 2: Quick Fire
- w erases the file and writes from the start
- a adds to the end and keeps what is there
Model answerw mode erases everything already in the file and writes from the start. a mode keeps what is there and adds the new data to the end.
- Variables are lost when the program ends, because they live in memory
- A file keeps the data permanently, so it can be loaded next time
Model answerVariables are held in memory and are lost when the program ends. A file keeps the data permanently in storage, so it can be loaded again next time.
- 1020
- split gives strings, so + joins them rather than adding
Model answer1020 is printed. split gives back strings, "10" and "20", and + joins strings together rather than adding them. int() would be needed to add them as numbers.
- The first time it runs, there is no file yet
- Otherwise it crashes; handling the error lets it start fresh
Model answerThe first time the program runs, the file does not exist yet. Without handling the error the program would crash; catching it lets the program start fresh with no scores.
Round 3: Big Think
- It opens scores.txt in read mode, and with closes it automatically
- It loops through each line of the file
- strip removes the newline from the end of the line
- split separates the name and the score at the comma
- It prints each name and score, such as Aisha scored 82
Model answerThe first line opens scores.txt in read mode, and using with means the file is closed automatically at the end. The for loop goes through each line of the file. strip removes the newline from the end of the line, and split separates it at the comma into the name and the score. Finally it prints each one, for example Aisha scored 82.
- A dictionary of names and scores
- A load subroutine reads the file when the program starts
- try and except handle the file not existing on the first run
- A save subroutine writes the file back, in write mode
- Each line holds name,score; split and int are used when loading
- A subroutine finds the top score, for example with max
- Each subroutine has one job, so it is easier to test and reuse
- with open closes the files automatically
Model answerI would store the scores in a dictionary, with each player's name as the key and their score as the value. A load_scores subroutine would read the file when the program starts, splitting each name,score line at the comma and using int to turn the score into a number. It would use try and except so that on the first run, when the file does not exist, the program starts with an empty dictionary instead of crashing. A show_top subroutine would use max to find the highest score, and a save_scores subroutine would write every name and score back to the file in write mode at the end. Each subroutine has one job, so each is easy to test and reuse, and using with open means the files are always closed automatically.
This or That
"w"Write mode starts the file again from empty. Append adds to the end."r"r reads the file. w would erase it.- 64 strip removes the newline, split makes ["Ben", "64"], and score gets the second part.
- Everything read from a text file is text Data read from a text file is a string, so int() turns it into a number before any maths.
- Each job can be read, tested and fixed alone Clear separate jobs make a program easier to read, to test and to fix.
['a', 'b', 'c']split cuts the string at every comma and returns a list.- 3 Each time w mode opens the file it is erased, so only the last 3 lines survive.
hi, with no spaces strip removes spaces and newlines from both ends of a string.
Memory Match
- A 6
open("f.txt", "r"): Opens a file to read it - B 4
open("f.txt", "w"): Opens a file and empties it first - C 2
open("f.txt", "a"): Opens a file to add to the end - D 3
.strip(): Removes spaces and newlines from both ends - E 1
.split(","): Cuts a string into a list at each comma - F 5
str(77): Turns a number into text