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

Lab: trace a loop, repair an infinite loop and write a totals program

Trace a loop with a table, repair a while loop that never ends and write a program that totals and counts.

  • 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 shop (invented) writes small programs to summarise its week. Program A:

total = 0
for n in range(1, 6):
    if n % 2 == 1:
        total = total + n
print(total)

Program B, which a trainee wrote to say Hi three times:

count = 0
while count < 3:
    print("Hi")

And Program C:

x = 10
while x > 0:
    x = x - 4
    print(x)

Tasks

Task 1 (4 marks)

Give the output of Program A and say what it adds.

Private: nothing you type here is sent or stored.

Task 2 (3 marks)

Program B never ends. Explain why and rewrite it so it prints Hi three times.

Private: nothing you type here is sent or stored.

Task 3 (3 marks)

Write the printed values of Program C.

Private: nothing you type here is sent or stored.

Task 4 (5 marks)

Write a program that uses a loop to add the multiples of 5 from 5 to 50 and counts how many there are, then prints both.

Private: nothing you type here is sent or stored.

Rubric and model answer

Task 1: trace program A (4 marks)

Model: the odd values 1, 3 and 5 are added, so total is 9 and the output is 9.

Task 2: repair program B (3 marks)

Model: count never changes, so count < 3 is always True. Add count = count + 1 inside the loop.

Task 3: trace program C (3 marks)

Model: 6, then 2, then -2. The loop ends because -2 > 0 is False.

Task 4: write a program (5 marks)

Model: total = 0, count = 0, for m in range(5, 51, 5): then total = total + m and count = count + 1; print total and count after the loop. Total is 275 and count is 10.

Marks so far: 0 of 15

Review with flashcards

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

Open the module flashcards