Proof Academy · Python · Journey 07

Test, debug and refine

Design tests that expose logic errors and use small functions to check program behaviour.

Lab and core lesson: 40–50 minutes, plus guided study · Builds on Functions and program structure

01 · Understand and predict

Choose tests that could prove you wrong

A syntax error stops Python from parsing a program. A runtime error occurs while a valid instruction is running. A logic error produces the wrong result even though the program runs. Use the traceback for the first two and compare predicted with actual output for the third.

Choose a normal case, the limits of the allowed range and values just beyond them. Add erroneous data that checks the program’s assumptions, such as a blank entry or letters where digits are required. Record expected results before running the tests so a surprising answer cannot become the expectation.

Validation checks whether data meets rules about format, presence, length or range. Authentication checks a claimed identity. A correctly formatted ID may still be unknown. An authentication exercise can look for a matching ID and a matching credential in the same record. Use invented data in practice.

def valid_hours(text):
    return text.isdecimal() and 1 <= int(text) <= 8

for value in ["4", "1", "8", "0", "9", "two"]:
    print(value, valid_hours(value))

Worked trace

  1. 4 checks a typical accepted value. 1 and 8 exercise the included limits.
  2. 0 and 9 are the neighbouring rejected numbers. These can expose a one-off error at either limit.
  3. The first comparison rejects 'two', so and skips the conversion. That avoids ValueError.
Which single test exposes a bug that uses < 8 where the specification requires <= 8?

From code to machine. Each test starts a fresh program run with a known input in this browser lab. This makes it easier to compare runs. Programs that save files or use shared state also need tests for what happens when you run them again.

Guided study

Read it, trace it, test it

Write down the rule you are testing

A passing example tells you that the program handled one input. It does not establish that every branch works. Start with a short statement of the expected behaviour, such as “hours must consist of decimal digits and have a value from 1 to 8 inclusive”. This contains two different checks. To test numeric range, choose well-formed numbers that vary in value. To test format, choose values that fail before a numeric range can be considered. If both features change at once, a failure gives less information about where to look.

CaseInputExpected outputWhat it checks
Normal4AcceptedA typical valid number
At minimum1AcceptedLower limit included
Just below0RejectedFirst value below the range
At maximum8AcceptedUpper limit included
Just above9RejectedFirst value above the range
EmptyblankRejectedPresence and format checked before conversion
Incorrect type3.5RejectedDecimal point excluded by the whole-number rule

Add a column for actual output after you run the program. If a case fails, note the first difference rather than labelling the whole program broken. If every case fails with the same exception, first repair the error that prevents the program reaching its decisions. Then repeat the same tests. This is a regression check: it helps show that a fix did not break behaviour that already worked.

Read a traceback from the bottom

The bottom line often identifies the kind of error. ValueError from int(text) points to a conversion of unsuitable text. IndexError points to a position that is not in the list or string. NameError can mean a typo or that a line used a variable before it was assigned. Use the traceback line number to locate the instruction that failed, then trace back to where the value came from. Fix the cause rather than changing a later line merely to avoid the message.

For a logic error there may be no traceback. Try a temporary print of the condition or of the values before and after an update. Run one failing case. Then remove the debug output before checking the required format. In the sandbox, use Run with my input for that one test, then Check test cases to run the provided suite. If the code times out, look for a loop whose condition never changes. Stop it, trace the update and try again with the smallest possible input.

Check that two fields belong together

For fictional club records, validating a code format does not tell you whether it appears in the list. Matching a code in one row and a practice word in another row also does not authenticate the claimed pair. The match must be performed on the same record. A known pair exercises the successful path. A known code with another record’s word can expose a faulty pair of separate searches. An unknown code and an empty word exercise different failure paths. Keep the mock data inside the exercise and never reuse a real credential.

Practise a Paper 2 change request

A starter function accepts a ticket code if it starts with A and ends with three digits, for example A007. It currently uses code[0] == "A" and code[1:].isdecimal(). Find two shortcomings. Repair it so that the entire string has exactly four characters, the first is uppercase A, and the last three are decimal digits. Write normal, boundary and erroneous tests, including a blank entry, and predict the results before running.

Test the format of the output too

A program can calculate the right number and still fail an exact comparison. Look for extra prompts, debug prints, added spaces and values printed in the wrong order. Compare the two outputs line by line. Only change output formatting once you know that the underlying calculation is correct.

Check your guided practice

A7 passes the faulty code even though the length is wrong. A blank entry causes an index error before reaching the digit check. Start with len(code) == 4, then check code[0] == "A" and code[1:].isdecimal(). Python evaluates the tests left to right and stops an and chain at the first false value. A007 passes, while A00, A0000, a007, A00X and a blank entry all fail. Re-run the original valid example after the repair.

02 · Run and repair

Reject text without a crash

The program accepts whole-number hours from 1 to 8 inclusive. It crashes when you enter two because it converts the string before checking its format. Repair it so it prints Rejected for every invalid input.

One line for input(). Leave the box empty to test a blank entry.

Ready to run.

Need a hint?

Read the raw text. Put isdecimal() first in an and condition so conversion only happens when the format is valid.

03 · Build independently

Match both fields in one record

Use a two-dimensional list of fictional club records: U01 with word robin, U02 with word fern and U03 with word oak. Write a function that checks one claimed code and practice word against the same row.

  • Read the code and word on separate lines. Match both case-sensitively. Use only the fictional data in the brief.
  • Print Match only if both values match one record. Print No match for a missing code, a wrong word or a word belonging to someone else.
  • Test an existing pair, an unknown code and a pair made from two different records. These three cases isolate different mistakes.

Enter one value per line. Each input() reads the next line.

Ready to run.

Need a hint?

Loop over the list of records. Inside the loop, compare the entered code and word with fields 0 and 1 from that same record. Return False only after checking all the rows.

04 · Explain and transfer

Explain your reasoning

Why does U01 with oak matter when both strings appear in the records?

Compare your explanation

The code and word belong to different rows. Searching for each string separately would accept the pair. The two comparisons must succeed on the same row.

Independent follow-up. Write a test table with an expected result, actual result and reason for each of your cases. Add a fourth fictional record and check that your program finds it without changing the matching function.

Original GCSE practice · Pearson Edexcel 1CP2 1.2.5, 1.2.7, 6.1.4–6.1.6 and 6.4.3–6.4.4. Download your .py file to keep it after leaving the page.

Next: Searching and sorting →