Python · 3.1
Dictionaries, Files and Error Handling
Name
Class
Date
Mark / 27
Section A
Circle the letter of the correct answer. One mark each.
- 1What does a dictionary store?1
- AA grid of values
- BAn ordered list of items
- COnly numbers
- DPairs of keys and values
- 2What does
student.get("email")return if there is no email key?1- ANone
- BA KeyError
- C0
- DAn empty string
- 3Which file mode preserves existing content?1
- A"r"
- B"x"
- C"a"
- D"w"
- 4Why use
with open(...)rather thanopen(...)?1- AThe file is closed automatically even if an error occurs
- BIt allows more modes
- CIt reads faster
- DIt compresses the file
- 5Which error occurs when converting the text 'hello' to an integer?1
- ATypeError
- BValueError
- CIndexError
- DKeyError
- 6What does
finallydo in a try block?1- AEnds the program
- BRuns only if there was no error
- CRuns only if there was an error
- DRuns whether or not an error occurred
- 7Why should you avoid a bare
except:?1- AIt only catches one error
- BPython does not allow it
- CIt hides real bugs including your own typos
- DIt is slower
- 8What is a tuple?1
- AAn ordered collection that cannot be changed
- BA type of file
- CA key value store
- DA collection with no duplicates
- 9What format is best for saving a dictionary to a file so it can be loaded back exactly?1
- AAn image file
- BJSON
- CA CSV file
- DA plain text file
- 10Which error occurs when you look up a dictionary key that does not exist using square brackets?1
- AIndexError
- BValueError
- CKeyError
- DNameError
Section B
Answer in the space provided. The number of marks tells you how many separate points to make.
- 1StateState one advantage of using a dictionary rather than a list to store a student's details.2
- 2ExplainExplain why the try and except structure is used, and give an example of when it would be needed.4
- 3WriteWrite a program that reads a file called marks.txt containing one number per line and prints the average, handling the case where the file does not exist.5
- 4ExplainExplain the difference between opening a file in write mode and append mode.3
- 5ExplainExplain why catching a specific exception is better than using a bare except that catches everything.3
Mark scheme
Section A
Section B
1 State one advantage of using a dictionary rather than a list to store a student's details. 2
One mark for each of the following, to a maximum of 2.
- Values are accessed by a meaningful name rather than a numeric position
- This makes the code easier to read and less error prone
Model answer. A dictionary lets each value be accessed by a meaningful key, so writing student["mark"] makes the intention completely clear. With a list you would have to remember that the mark happened to be stored at index 2, which is far harder to read and very easy to get wrong, especially if the order of the fields ever changes.
2 Explain why the try and except structure is used, and give an example of when it would be needed. 4
One mark for each of the following, to a maximum of 4.
- It attempts code that might cause an error
- If the error occurs the except block runs instead of the program crashing
- Gives a valid example such as converting user input or opening a file
- Explains that this makes the program robust
Model answer. The try and except structure is used so a program can attempt something that might fail without crashing if it does. The code inside try is executed, and if it raises the named exception then Python jumps straight to the matching except block instead of stopping the program. A common example is converting user input to a number: if the user types letters, int() raises a ValueError, and without handling it the program would crash and the user would lose their work. With try and except the program can display a clear message and ask again. Handling errors like this is what makes a program robust, which means it continues to behave sensibly even when things go wrong.
3 Write a program that reads a file called marks.txt containing one number per line and prints the average, handling the case where the file does not exist. 5
One mark for each of the following, to a maximum of 5.
- Uses try and except around the file operation
- Opens the file for reading
- Converts each line into a number
- Calculates and prints the average
- Catches FileNotFoundError with a helpful message
Model answer. try: with open("marks.txt", "r") as file: marks = [int(line.strip()) for line in file if line.strip()] if len(marks) == 0: print("The file is empty.") else: print(f"Average: {sum(marks) / len(marks):.1f}") except FileNotFoundError: print("marks.txt could not be found.") except ValueError: print("The file contains something that is not a number.") Using with open means the file closes automatically. Each line is stripped of its newline before being converted, and blank lines are skipped. The empty file case is checked separately, because dividing by zero would otherwise raise its own error. Two specific exceptions are caught rather than using a bare except, so genuine bugs in the code are not hidden.
4 Explain the difference between opening a file in write mode and append mode. 3
One mark for each of the following, to a maximum of 3.
- Write mode erases everything already in the file
- Append mode adds to the end and keeps existing content
- Append should be used when previous data must be kept
Model answer. Opening a file in write mode empties it completely before anything is written, so every piece of data previously stored in that file is lost. Opening in append mode leaves the existing contents intact and adds anything written to the end. Write mode is appropriate when the entire contents are being replaced, such as saving a complete updated set of records. Append mode is essential whenever a single new record is being added to data that must be preserved, for example writing one more high score to a file that already contains a list of them.
5 Explain why catching a specific exception is better than using a bare except that catches everything. 3
One mark for each of the following, to a maximum of 3.
- A bare except catches every error including ones you did not anticipate
- This hides genuine bugs such as typos in variable names
- Catching a specific exception means only the expected problem is handled and other errors are still reported
Model answer. A bare except catches absolutely every exception, including ones the programmer never anticipated. That means a genuine bug elsewhere in the try block, such as a misspelled variable name raising a NameError, is silently swallowed and replaced with whatever message the except block prints. The program appears to handle the situation while actually hiding a real fault, which can take a very long time to track down. Naming the specific exception, such as except ValueError, means only the problem you actually expected is handled, and any other error still stops the program and reports itself properly so it can be found and fixed.