Specialty Digest

Global English editionLearners’ Study Dashboard — in development
The Knowledge Library for All

Flashcards: open the module flashcards (end-of-module review with workplace questions).

Online Courses / University Track / Python from Zero

Module 4 · Lab

Lab: trace collection code, repair a KeyError and write a counting program

Trace list and dictionary code, repair a lookup that fails and write a program that counts items.

  • 50 minutes
  • 15 marks
  • Self-marked

50 minutes. Self-marked against the rubric. 15 marks. In the full course this counts toward the labs and cases share (15% of the course grade). Write your answers in the boxes, then open the model answer and tick each mark you earned honestly. Nothing is sent or stored.

Scenario (invented)

A small shop (invented) keeps stock in Python. Program A:

items = [3, 8, 5]
items.append(6)
print(len(items))
print(items[-1])
print(sum(items))

Program B:

stock = {"pen": 5}
print(stock["ink"])

Program C:

d = {"a": 1}
d["b"] = 2
d["a"] = d["a"] + 10
print(d)

Tasks

Task 1 (4 marks)

Give the three lines Program A prints.

Private: nothing you type here is sent or stored.

Task 2 (3 marks)

Program B stops with an error. Name it and give two ways to avoid it.

Private: nothing you type here is sent or stored.

Task 3 (3 marks)

State what Program C prints.

Private: nothing you type here is sent or stored.

Task 4 (5 marks)

Write a program that counts how many times each colour appears in ["red", "blue", "red"] and prints the dictionary.

Private: nothing you type here is sent or stored.

Rubric and model answer

Task 1: trace program A (4 marks)

Model: 4 (three items plus one appended), 6 (the last item), 22 (3 + 8 + 5 + 6).

Task 2: repair program B (3 marks)

Model: a KeyError, because "ink" is not a key. Check with if "ink" in stock first, or use stock.get("ink", 0).

Task 3: trace program C (3 marks)

Model: {'a': 11, 'b': 2}. The key b is added, and a is updated from 1 to 11.

Task 4: write a counter (5 marks)

Model: counts = {}, then for c in colours: with if c in counts add 1, else set to 1; print counts. It prints red 2 and blue 1.

Marks so far: 0 of 15

Review with flashcards

Test yourself on this module with workplace flashcards and detailed answers.

Open the module flashcards