6.1.2 – Read, analyse and refine programs

6.1.2 – Read, analyse and refine programs

Trace state in a complete program, connect code to its requirements, and refine behaviour while checking that unaffected results stay correct.

Follow execution and changing state

Reading a program means establishing what actually happens, rather than guessing from its variable names. Find the data, the first call, the conditions and where each result is stored. This complete program receives a nonempty list of integer scores and counts those at least the target.

Python
def analyse_scores(scores, target):
    total = 0
    count = 0
    for score in scores:
        total = total + score
        if score >= target:
            count = count + 1
    mean = total / len(scores)
    return [mean, count]

scores = [7, 5, 8, 6]
result = analyse_scores(scores, 6)
print("Mean: " + str(result[0]))
print("Target reached: " + str(result[1]))

Python makes the definition available, then creates the list and reaches the call. It does not run the function body simply because it encounters def.

Current scoreTotal after additionConditionCount after decision
77True1
512False1
820True2
626True3

After the loop, mean becomes 26 / 4 = 6.5. The returned list is stored in result before either print runs.

Output
Mean: 6.5
Target reached: 3

Trace the value at the moment a statement executes. The count stays unchanged on a false condition; it does not reset. Equality is included because the comparison is >=.

Explain how code meets a requirement

Analysis links a requirement to responsible code and then to its effect. Naming for does not by itself explain why all scores contribute.

  • Initialising total before the loop starts an empty accumulation.
  • Iterating over scores visits every supplied item once.
  • Adding the current score inside that loop includes every value in the sum.
  • Updating count inside the selection adds one only for a qualifying score.
  • Dividing after the loop uses the completed total, not a partly accumulated value.

These links also expose assumptions. A nonempty list makes division by its length safe. If the list could be empty, the requirement would need to define the expected result; blindly dividing by zero is not acceptable.

Continue this lesson.

You’re previewing NovaLearn without an account. Create a free account to read the rest.

Create free account