PCAP Code Tracing: Python Practice and Readiness Review
Introduction
This PCAP code tracing lesson closes the PCAP-31-03 course. It covers all five sections of PCAP-31-03: Modules and Packages (12%, 6 items), Exceptions (14%, 5 items), Strings (18%, 8 items), Object-Oriented Programming (34%, 12 items) and Comprehensions, Lambdas, Closures, and I/O (22%, 9 items). The exam has 40 questions in 65 minutes, so you have on average about 100 seconds per item, and code-reading practice helps you apply the syllabus. Knowing the rules is necessary, but it is not enough: you must apply them quickly and without mistakes while reading every relevant detail.
The first half of this lesson teaches a tracing technique and applies it to twelve tracing topics, each one built around a classic trap. The second half is a readiness review: a table to locate weak areas, a time plan for the exam, and a study plan for the last week. After this lesson, take the course practice assessments under exam conditions. This course targets PCAP-31-03, available until November 30, 2027; the newer PCAP-31-04 has a different syllabus and scoring requirements.
Learning objectives
After this lesson you can:
- Trace a code sample with a state table, and avoid the most common reading errors.
- Recognise the twelve recurring traps of the exam: shared defaults, late binding, class versus instance attributes, name mangling,
isinstancedirection, encodings, and others. - Decide quickly when to eliminate options instead of computing the answer.
- Evaluate your own readiness by objective and plan a short revision.
- Manage the 65 minutes of the exam.
A tracing technique that works
Most wrong answers on a code item come from the same cause: the candidate reads the code as if it did what its author meant, instead of what it does. A disciplined trace removes this bias. Use four habits.
Habit 1: write the state. During practice, make a column for each variable, attribute or file position. Update it after every statement. Writing down intermediate values reduces mistakes when several objects or aliases are involved.
Habit 2: distinguish definition from execution. Evaluating def or lambda creates a function; calling an ordinary function runs its body. Defaults are evaluated at definition time, and decorators are applied then. A generator function instead starts its body when its iterator is advanced. A class body runs when its class statement executes.
Habit 3: ask "same object or copy?" Assignment, default arguments, append, slicing and += have different effects on identity. A slice of a list is a new list, while a name assigned from another name is the same object.
Habit 4: finish the program. Check what happens after the last visible statement, for example finally blocks and file closing, and check the exact print format: print adds a space between arguments and a newline at the end, and repr and str differ.
When the code is too long to trace, use elimination: options that cannot be produced by any reading of the code (wrong type, wrong exception class, impossible count) can be removed in seconds.
Twelve Python code tracing topics
Cover each explanation, trace the code, then compare your reasoning with the stated output. The final topic reviews file operations rather than presenting a standalone snippet.
Trap 1: super() and the order of initialisation
class A:
def __init__(self): self.x = 1
def show(self): return self.x
class B(A):
def __init__(self):
super().__init__(); self.x += 1
print(B().show(), B.__mro__[1].__name__, B.__bases__[0].__name__)Output: 2 A A. The child calls the parent's constructor first, so x is 1, then adds one. If super().__init__() were called after the addition, self.x += 1 would raise AttributeError, because x would not exist yet. The method resolution order is B, A, object, so the item at index 1 is A.
Trap 2: a mutable default argument
def f(n, acc=[]):
acc.append(n); return acc
print(f(1), f(2), f(3, []))Output: [1, 2] [1, 2] [3]. The default list is created once, when def runs. The first two calls share it and return the same object. Because print evaluates all arguments before it prints, both of the first two values show the final content [1, 2]. The third call passes its own list. This single item combines two traps: shared state and evaluation order.
Trap 3: slicing and string methods
s = "Python"
print(s[1:4], s[::-2], s.find("th"), s.center(10, "*"), "a-b-c".rsplit("-", 1))Output: yth nhy 2 **Python** ['a-b', 'c']. The slice 1:4 includes index 1 and excludes index 4. The step -2 starts at the end: n, h, y. find returns the index of the first occurrence, here 2. center pads on both sides with the given character, and rsplit(sep, 1) splits only once from the right. Check each index by writing the letters with their positions: P0 y1 t2 h3 o4 n5.
Trap 4: exception chaining and finally
try:
try: 1/0
except ZeroDivisionError as e: raise KeyError("k") from e
finally: print("f1")
except LookupError as e2:
print(type(e2.__cause__).__name__, e2.args)Output: f1 then ZeroDivisionError ('k',). The inner finally runs before the exception leaves the inner try. KeyError is a subclass of LookupError, so the outer clause matches. The from e sets __cause__, and args holds the tuple of arguments given to the exception.
Trap 5: late binding in a comprehension
x = [lambda: i for i in range(3)]
print([g() for g in x], [i for i in range(3) if i % 2 == 0])Output: [2, 2, 2] [0, 2]. All three lambdas read the same variable i, whose value is 2 after the loop. The second comprehension filters even numbers. A fix for the first list is lambda i=i: i, which evaluates i at creation.
Trap 6: class attribute versus instance attribute
class C:
n = 0
def __init__(self): self.n += 1
a, b = C(), C(); print(C.n, a.n, b.n)Output: 0 1 1. The expression self.n += 1 reads the class attribute 0, adds one, and stores the result in the instance, creating an instance attribute. The class attribute is untouched. To count instances, write C.n += 1.
Trap 7: characters, code points and bytes
print(bytes("é", "utf-8"), "é".encode("latin-1"), ord("é"), chr(233) == "é")Output: b'\xc3\xa9' b'\xe9' 233 True. The same character gives two bytes in UTF-8 and one byte in Latin-1. The code point is 233 in both cases, and chr(233) returns the character.
Trap 8: name mangling and a new attribute
class D:
def __init__(self): self.__v = 1
def get(self): return self.__v
d = D(); d.__v = 5; print(d.get(), d.__dict__)Output: 1 {'_D__v': 1, '__v': 5}. Inside the class, __v is stored as _D__v. Outside the class, d.__v = 5 is not mangled and creates a different attribute. get still reads the mangled name, so it returns 1.
Trap 9: direction of isinstance and issubclass
This snippet reuses classes A and B from Trap 1; define them first if running it separately.
print(issubclass(B, A), isinstance(A(), B), hasattr(B, "show"))Output: True False True. B is a subclass of A. A parent instance is not an instance of the child. hasattr(B, "show") is True because the attribute is inherited.
Trap 10: separate closures with nonlocal
def counter():
c = 0
def inc():
nonlocal c; c += 1; return c
return inc
i1, i2 = counter(), counter(); print(i1(), i1(), i2())Output: 1 2 1. Every call to counter creates a new c, so the two closures have independent state. Without nonlocal, c += 1 would raise UnboundLocalError.
Trap 11: format alignment
print("{:>5}|{:<5}|{:^5}".format("a","b","c"), "Ab1".swapcase())Output: a|b | c aB1. > aligns right, < aligns left, and ^ centres, with the extra space on the right for an odd padding. swapcase changes letters only.
Trap 12: the shape of a file loop
Reading a file with readline() once and then iterating over it with for skips the first line in the loop. A call to read() twice returns an empty string the second time. Opening with "w" erases the file at open time. These three file traps appear in many variations; check the position every time.
Worked example: a full exam-style item, solved in four steps
Statement. What is printed?
class Base:
tags = []
def add(self, t):
self.tags.append(t)
return self
class Child(Base):
def __init__(self):
self.tags = list(Base.tags)
a, b = Base(), Child()
a.add("x").add("y")
b.add("z")
print(Base.tags, b.tags, len(a.tags))Step 1: state before the calls. Base.tags is one list, []. a has no attribute tags of its own. b has its own attribute: a copy of the empty list made in __init__.
Step 2: a.add("x").add("y"). add returns self, so the calls chain. self.tags for a finds the class attribute (the instance has no attribute with that name), and append mutates the shared list. After the two calls, Base.tags is ['x', 'y'].
Step 3: b.add("z"). For b, self.tags is the instance list, so z goes into b.tags only, which becomes ['z'].
Step 4: the print. Base.tags is ['x', 'y'], b.tags is ['z'], and len(a.tags) is 2.
['x', 'y'] ['z'] 2Why other answers are wrong. The result ['x', 'y', 'z'] assumes that b shares the class list, but Child.__init__ made a copy. A result of [] for Base.tags assumes that appending through an instance cannot change the class attribute, which is false for a mutable object found through lookup. An AttributeError does not occur because a finds tags on its class.
Comparison: how to answer common item patterns
| Item pattern | Fast method | Frequent mistake |
|---|---|---|
| "What is printed?" with a loop | State table, update per iteration | Skipping the last iteration |
| "Which exception is raised?" | Find the first failing statement, then the class | Choosing a parent class |
| "Select two" | Test each option separately | Choosing only one true statement |
| String slicing | Write letters with indexes | Off-by-one at the stop index |
| Import tracing | List what runs at import, in order | Forgetting that imports run only once |
| Class attributes | Ask "read or assign?" | Believing += changes the class attribute |
| File operations | Track mode and position | Ignoring truncation by "w" |
| Closures | Ask "when is the value read?" | Reading at definition time |
If late binding remains unclear, revisit Python closure capture timing. For shared lists and counters, review Python instance, class and private attributes.
Readiness review
Use this table to evaluate yourself. For each objective, you should be able to explain the rule and give a short example without notes. Mark each objective green, orange or red, using the section rows below as an index.
| Section | Objectives | Key checks |
|---|---|---|
| Modules and Packages (6 items) | 1.1 to 1.5 | import forms, sys.path, __name__, __all__, __init__.py, dir(), math, random, platform |
| Exceptions (5 items) | 2.1, 2.2 | try/except/else/finally, order of clauses, raise, from, assert, custom classes, args |
| Strings (8 items) | 3.1 to 3.3 | ASCII, Unicode, ord, chr, encodings, slicing, find, split, join, format, comparisons |
| OOP (12 items) | 4.1 to 4.6 | Classes, self, attributes, mangling, super(), inheritance, isinstance, __str__, __dict__, introspection |
| Functional and I/O (9 items) | 5.1 to 5.5 | Comprehensions, lambda, map, filter, closures, generators, open, modes, bytearray, errno |
Rate each individual objective listed in the table, rather than just its five section rows. Revisit every red objective before taking an assessment; if none are red, attempt an assessment and use its explanations to find remaining gaps. Object-Oriented Programming has the most items (12 of 40), so an orange row there costs more than an orange row in Modules.
Exam-day plan
| Phase | Time | Action |
|---|---|---|
| First pass | 40 minutes | Answer every item you can solve in about one minute; mark the rest |
| Second pass | 15 minutes | Return to marked items and trace carefully |
| Final check | 10 minutes | Check selections for "select two" items and unanswered items |
Practical advice: read the question statement before the code, because it tells you whether you must find the output, the exception, or the true statements. Do not leave an item unanswered, since a wrong answer costs nothing more than a blank. The published PCAP-31-03 format allocates 10 additional minutes for the non-disclosure agreement and tutorial. Follow the materials, navigation and review rules provided for your actual delivery method. The pass threshold is 70%. Remember that the official scoring weights sections differently from item counts, so practice scores in this course are a guide, not an official score.
Common pitfalls and exam tips
| Pitfall | What happens | Remedy |
|---|---|---|
| Rushing through familiar-looking code | You miss a single changed character | Read every line, including default arguments |
| Computing instead of eliminating | Time loss | Remove options with wrong types or classes |
Ignoring print formatting |
Wrong spacing in the answer | Reproduce separators and newline |
| Assuming a name exists | NameError or AttributeError |
Check that each name was defined before use |
| Trusting memory of a method name | Mistakes such as str.index versus str.find |
Recall what is returned on failure |
| Studying only new topics at the end | Old topics fade | Alternate sections in the last week |
Exam tip. If two options differ by only one detail, the detail is the subject of the item. Trace that detail precisely.
Exam tip. When a question mentions "which statements are true", test each statement independently, as if it were a separate true or false question.
Exam tip. If an exception propagates out of the top-level script, later top-level statements do not run. Enclosing finally blocks execute during propagation; an exception handled by an outer caller does not necessarily end the whole application.
End-of-lesson case study
Situation. A candidate scores 62% on a first practice assessment: almost perfect in Modules and Exceptions, 50% in Strings, 55% in OOP and 40% in Functional and I/O. The candidate has one week. Propose a plan and explain the priorities.
Solution, commented. Use section weights to prioritise revision, and treat this calculation as a study estimate rather than a reproduction of official scoring. Raising OOP from 55% to 75% contributes about 0.34 × 20 = 6.8 percentage points; Functional and I/O from 40% to 70% contributes 0.22 × 30 = 6.6 points; Strings from 50% to 75% contributes 0.18 × 25 = 4.5 points. The estimated improvement is 17.9 points. The initial 62% is a separate practice result: without its exact question distribution and scoring rules, it cannot be reconciled precisely with these approximate section percentages or converted into an official score.
Allocate two days to Functional and I/O (closures, generators and file modes), two days to OOP (attributes, inheritance and introspection), one day to Strings, one day to a fresh assessment, and the final day to reviewing errors. Keep tracing the examples that caused mistakes. These priorities reflect both the learner’s weak areas and the official section weights.
Key terms
- Trace: a step-by-step execution of code on paper, with a state table.
- Late binding: reading a captured variable when the function is called, not when it is created.
- Shared default: a default argument object that is created once and reused by all calls.
- Mangled name: the form
_Class__namethat Python gives to a name starting with two underscores. - Elimination: removing options that no reading of the code can produce.
- Readiness: the ability to apply each objective without notes.
Summary checklist
- I trace code with a state table and finish the program, including
finally. - I recognise the twelve traps in this lesson and can fix each one.
- I allocate items by section count, not only by percentage.
- I have a time plan for 40 items in 65 minutes.
- I rated each objective green, orange or red.
- I revise weak areas first and take the practice assessments in exam conditions.
Official sources
- Python Institute, PCAP-31-03 exam page: https://pythoninstitute.org/pcap-31-03 (opens in a new tab)
- Python Institute, PCAP-31-03 exam syllabus: https://pythoninstitute.org/pcap-31-03-exam-syllabus (opens in a new tab)
- Python documentation, data model: https://docs.python.org/3.14/reference/datamodel.html (opens in a new tab)
- Python documentation, execution model (naming and binding): https://docs.python.org/3.14/reference/executionmodel.html (opens in a new tab)
- Python documentation, built-in exceptions: https://docs.python.org/3.14/library/exceptions.html (opens in a new tab)
