Back to the topic

The mark scheme starts on a new page, so you can print pages one and two for a student and keep the last page yourself. Everything prints in black on white whichever theme you are using.

Python · 3.1

Dictionaries, Files and Error Handling

Section A: 10 multiple choice questions, 10 marks. Section B: 5 written questions, 17 marks. Total 27 marks.

Name

Class

Date

Mark  / 27

Section A

Circle the letter of the correct answer. One mark each.

  1. 1What does a dictionary store?1
    1. AA grid of values
    2. BAn ordered list of items
    3. COnly numbers
    4. DPairs of keys and values
  2. 2What does student.get("email") return if there is no email key?1
    1. ANone
    2. BA KeyError
    3. C0
    4. DAn empty string
  3. 3Which file mode preserves existing content?1
    1. A"r"
    2. B"x"
    3. C"a"
    4. D"w"
  4. 4Why use with open(...) rather than open(...)?1
    1. AThe file is closed automatically even if an error occurs
    2. BIt allows more modes
    3. CIt reads faster
    4. DIt compresses the file
  5. 5Which error occurs when converting the text 'hello' to an integer?1
    1. ATypeError
    2. BValueError
    3. CIndexError
    4. DKeyError
  6. 6What does finally do in a try block?1
    1. AEnds the program
    2. BRuns only if there was no error
    3. CRuns only if there was an error
    4. DRuns whether or not an error occurred
  7. 7Why should you avoid a bare except:?1
    1. AIt only catches one error
    2. BPython does not allow it
    3. CIt hides real bugs including your own typos
    4. DIt is slower
  8. 8What is a tuple?1
    1. AAn ordered collection that cannot be changed
    2. BA type of file
    3. CA key value store
    4. DA collection with no duplicates
  9. 9What format is best for saving a dictionary to a file so it can be loaded back exactly?1
    1. AAn image file
    2. BJSON
    3. CA CSV file
    4. DA plain text file
  10. 10Which error occurs when you look up a dictionary key that does not exist using square brackets?1
    1. AIndexError
    2. BValueError
    3. CKeyError
    4. DNameError

Section B

Answer in the space provided. The number of marks tells you how many separate points to make.

  1. 1StateState one advantage of using a dictionary rather than a list to store a student's details.2
  2. 2ExplainExplain why the try and except structure is used, and give an example of when it would be needed.4
  3. 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
  4. 4ExplainExplain the difference between opening a file in write mode and append mode.3
  5. 5ExplainExplain why catching a specific exception is better than using a bare except that catches everything.3

Mark scheme

Section A

1D2A3C4A5B6D7C8A9B10C

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.