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

Lab: trace function code, repair a unit error and write a tested function

Trace calls, repair a function that silently mixes units and write and test a small function.

  • 50 minutes
  • 16 marks
  • Self-marked

50 minutes. Self-marked against the rubric. 16 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 workshop (invented) uses two functions. Program A:

def double(n):
    return n * 2

def show(n):
    print(n * 2)

x = double(5)
y = show(5)
print(x)
print(y)

Program B converts a weight to the unit the shipping function expects, which is kilograms:

def shipping_cost(kg):
    return kg * 4

weight_lb = 22
print(shipping_cost(weight_lb))

Program C:

def f(a, b):
    c = a + b
    return c

print(f(2, 3))
print(c)

Tasks

Task 1 (4 marks)

Give every line Program A prints, in order.

Private: nothing you type here is sent or stored.

Task 2 (4 marks)

Program B passes pounds to a function that expects kilograms. Explain the effect and rewrite it correctly. One pound is about 0.4536 kg.

Private: nothing you type here is sent or stored.

Task 3 (3 marks)

State what Program C prints and why.

Private: nothing you type here is sent or stored.

Task 4 (5 marks)

Write a function is_even(n) that returns True when n is even, and give three test calls with expected results.

Private: nothing you type here is sent or stored.

Rubric and model answer

Task 1: trace program A (4 marks)

Model: 10 (from the call to show), then 10 (x), then None (y), because show prints but does not return.

Task 2: repair program B (4 marks)

Model: the function treats 22 as kilograms, so the cost is for 22 kg instead of about 10 kg, which is over twice too high. Convert first: kg = weight_lb * 0.4536, then shipping_cost(kg), with the unit named in the variable.

Task 3: trace program C (3 marks)

Model: 5, then a NameError, because c is local to f and does not exist outside it.

Task 4: write and test a function (5 marks)

Model: def is_even(n): return n % 2 == 0. Tests: is_even(4) is True, is_even(7) is False, is_even(0) is True.

Marks so far: 0 of 16

Review with flashcards

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

Open the module flashcards