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 7 · Lab

Lab: read errors, handle a failure, write tests and debug a function

Name errors from tracebacks, handle a bad entry, write tests with edges and trace a faulty function.

  • 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) uses these programs. Program A:

items = [3, 8, 5]
print(items[3])

Program B reads a quantity typed by a customer:

qty = int(input("Quantity: "))
print(qty * 4)

Program C should return the larger of two numbers:

def bigger(a, b):
    if a > b:
        return b
    return a

Tasks

Task 1 (3 marks)

Name the error Program A gives and say why.

Private: nothing you type here is sent or stored.

Task 2 (4 marks)

Program B stops if the customer types abc. Rewrite it so it prints a message and does not stop.

Private: nothing you type here is sent or stored.

Task 3 (4 marks)

Write two assert lines that expose the fault in Program C.

Private: nothing you type here is sent or stored.

Task 4 (4 marks)

Explain the fault in Program C and give the repaired function.

Private: nothing you type here is sent or stored.

Rubric and model answer

Task 1: name the error (3 marks)

Model: an IndexError. The list has positions 0 to 2, so position 3 does not exist.

Task 2: handle the entry (4 marks)

Model: put int(input(...)) in a try block, with except ValueError printing a message such as Please enter a whole number.

Task 3: test Program C (4 marks)

Model: assert bigger(5, 2) == 5 fails because the function returns 2, and assert bigger(1, 9) == 9 fails because it returns 1. A test with equal numbers, such as assert bigger(4, 4) == 4, passes by accident and hides the fault.

Task 4: debug Program C (4 marks)

Model: the returns are the wrong way round, so it gives the smaller number. Return a when a is greater and b otherwise, then rerun all tests.

Marks so far: 0 of 15

Review with flashcards

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

Open the module flashcards