Grade by Grade
A. Programming Concepts and Skills · Data Types, Files and Expressions

Code Maintenance: Using Documentation to Fix Errors Independently

A4.1About 65 minutes
Learning goals
  • I can read a traceback from the bottom up and find the line and the call that caused an error.
  • I can use help(), dir(), docstrings and the official Python documentation to check what a function really does.
  • I can follow a repeatable debugging cycle (reproduce, read, isolate, check documentation, fix and retest).
  • I can judge online answers and write a minimal example when asking for help.

Words to know

traceback
Python's error report: the chain of function calls that led to an exception, ending with the exception's type and message.
syntax error
Code that breaks the language's grammar, so the program cannot start (e.g. a missing colon).
run-time error (exception)
An error that happens while the program runs, such as ZeroDivisionError or FileNotFoundError.
logic error
The program runs without crashing but produces the wrong result.
API documentation
The official description of what each function, class and module does, its parameters and its return value.
minimal reproducible example
The shortest complete program that still shows a problem; it makes the cause easy to see and to ask about.
rubber duck debugging
Explaining your code line by line out loud (even to a rubber duck); describing it often reveals the bug.

Becoming your own help desk

In ICS3U you learned the three kinds of errors (syntax, run-time and logic) and practised fixing them. In Grade 12 the expectation changes: you should be able to work independently, using support documentation (IDE help, tutorials, websites, user manuals) to solve problems yourself. In university and at work, nobody will look over your shoulder; the documentation is your teacher.

This lesson gives you a process and the tools: how to read Python's error reports in full, where Python's own documentation lives, and how to use it to answer "what does this function really do?"

def average(marks):
return sum(marks) / len(marks)
def report(student, marks):
print(student, round(average(marks), 1))
report("Amara", [88, 92, 79])
report("Ben", [])

This program prints one line and then crashes. The traceback it produces is shown next.

Traceback (most recent call last):
File "main.py", line 8, in <module>
report("Ben", [])
~~~~~~^^^^^^^^^^^
File "main.py", line 5, in report
print(student, round(average(marks), 1))
~~~~~~~^^^^^^^
File "main.py", line 2, in average
return sum(marks) / len(marks)
~~~~~~~~~~~^~~~~~~~~~~~
ZeroDivisionError: division by zero

The traceback from Python 3.13 (folder names removed). Read it from the bottom up: the last line names the error, and the frames above it show the chain of calls that led there, ending with the line that failed. The ~ and ^ markers point at the exact part of the line; older versions of Python show fewer markers.

Traceback (most recent call last):the calls, oldest firstFile "main.py", line 8, in <module>1. where it startedFile "main.py", line 5, in report2. called averageFile "main.py", line 2, in average3. the failing lineZeroDivisionError: division by zeroread this first!
The parts of a traceback. Start at the last line (the exception type and message), then look at the frame just above it (the line where it happened), then work upward to see which call passed the bad data. Here report("Ben", []) passed an empty list.

Where the documentation is

  • Inside Python: help(len), help(str.split), help("open"). Every function with a docstring (including your own) shows up here. dir(obj) lists the names available on an object.
  • The official documentation, docs.python.org: the Tutorial (learning), the Library Reference (every built-in function and standard module, such as Built-in Functions, csv, json, sqlite3) and the Language Reference (exact grammar rules). Make sure the version selector matches your Python.
  • Your editor or IDE: hovering over a name, or pressing the shortcut for "go to definition" or "show documentation", shows the same docstrings. Autocomplete lists methods as you type.
  • Tutorials, forums and AI assistants: useful for ideas, but they can be out of date or wrong. Check any answer against the official documentation and test it before relying on it.
nums = [30, 4, 15]
result = nums.sort()
print(result, nums)
name = "snow day"
name.replace("snow", "SNOW")
print(name)
print(name.replace("snow", "SNOW"))

Two classic surprises that the documentation explains. list.sort() sorts in place and returns None. Strings are immutable, so str.replace returns a new string and leaves the original alone. Output, line by line: None [4, 15, 30] | snow day | SNOW day

help(str.replace)

help() shows the documentation built into Python. The first sentence answers the question: replace "Return[s] a copy". (The exact wording and layout differ a little between Python versions; this is Python 3.13.) dir(str) lists every method a string has.

Worked example

Example 1: Fix it with the documentation

A student's program writes a list of names to a file, but the file ends up as one long line: AmaraBenChloé. The code is f.writelines(names). Use the documentation to explain and fix it.

  1. Reproduce: run the program and open the file. Yes: one line, no spaces.
  2. Read: there is no error message, so this is a logic error. The question becomes "what does writelines actually do?"
  3. Docs: help(f.writelines) (or the io module page on docs.python.org) says it writes a list of lines to the stream and that line separators are not added, so each string should end with a newline if you want separate lines.
  4. Fix: f.writelines(name + "\n" for name in names), or for name in names: print(name, file=f).
  5. Retest: open the file again; each name is on its own line. Add the fix to your notes so you do not need to look it up again.

writelines does not add newlines. Add "\n" to each string.

1. Reproduce2. Read the message3. Isolate4. Check the docs5. Fix and retestrepeat until the tests pass
An independent debugging cycle. The documentation step (green) is where you check what a function really does, instead of what you assumed it does.

A debugging cycle you can always fall back on

  1. Reproduce the problem reliably. Note the exact input that causes it.
  2. Read the whole message: exception type, message text, line number, and the call chain.
  3. Isolate: cut the program down to the smallest version that still fails (a minimal reproducible example). Add print statements or use a debugger to check values just before the failing line.
  4. Check the documentation for every function involved. Many bugs come from an assumption: that sort() returns the list, that replace changes the string, that int() rounds, that "w" mode appends.
  5. Fix and retest with the original input and the earlier test cases, to make sure nothing else broke. (Formal testing plans are part of the sibling unit Algorithm Design and Analysis.)
Worked example

Example 2: Syntax errors and what Python suggests

Each line below has a syntax or name error. Predict Python 3.13's message, then fix it.

  1. print("hi"
  2. if x == 1 (followed by an indented line)
  3. x = [1, 2 3]
  4. prnt("hi")
  1. 1. SyntaxError: '(' was never closed. Add the closing parenthesis.
  2. 2. SyntaxError: expected ':'. Add a colon after if x == 1.
  3. 3. SyntaxError: invalid syntax. Perhaps you forgot a comma? Write [1, 2, 3].
  4. 4. NameError: name 'prnt' is not defined. Did you mean: 'print'? Fix the spelling.
  5. Modern Python (3.10 and later) gives much more helpful syntax messages than older versions. If your school computer has an older version, the message may just say invalid syntax; then look at and just before the marked spot, because the real mistake is often on the previous line (an unclosed bracket, for example).

Python's message names the problem and often suggests the fix; read it fully before changing anything.

Asking for help well

If you are still stuck, post or send a minimal reproducible example: the shortest complete program that shows the problem, the exact input, the full error message (copied, not retyped), what you expected, and what you have already tried. Writing it often makes you spot the bug yourself. Never paste passwords, personal data or private keys into a public forum or an online tool.

Just for fun

The most powerful debugging tool ever invented is a rubber duck. Programmers really do explain their code to one, line by line, and halfway through the explanation the bug usually confesses.

Hands-on activity

Documentation scavenger hunt

You need: Python and a web browser.

For each question, find the answer in help() and on docs.python.org, then confirm it by running a one-line test. Write down where you found it.

Step 1. What does round(2.5) return, and why? (Look up round in Built-in Functions.)

Step 2. What does str.split() do with several spaces in a row when no separator is given? What about str.split(" ")?

Step 3. What does list.pop() return, and what happens on an empty list?

Step 4. What is the difference between json.dump and json.dumps?

Step 5. Which open() mode creates a file but fails if it already exists?

What to look for: 2 (round half to even); runs of whitespace count as one separator with no argument, but " " gives empty strings between repeated spaces; pop returns the removed item and raises IndexError on an empty list; dump writes to a file and dumps returns a string; mode "x".

Your turn

1

In the traceback for the marks program, which line of main.py actually failed, and which call passed the bad data?

2

Suggest a fix for the marks program so an empty list does not crash it.

3

What does print([3, 1, 2].sort()) print? Where would you confirm why?

4

Which built-in function lists the methods a value has?

5

A message ends with Did you mean: 'sqrt'? after math.sqroot(4). What is the error type and fix?

6

Put these debugging steps in order: check the docs, fix and retest, reproduce, isolate, read the message.

7

Why should you check that the online documentation version matches your Python version?

More practice: warm-up

1

Which line of a traceback should you read first?

2

What does help(len) show?

3

Name the three kinds of errors.

4

Is None returned by list.sort() or by sorted()?

5

What is the official Python documentation website?

More practice: on your own

1

A program prints TypeError: can only concatenate str (not "int") to str for the line print("Age: " + age). Explain and fix it, and say where in the docs you could read about str().

2

The code words = line.split(",") gives ['a', ' b', ' c'] for the line a, b, c. Use the documentation of str.strip to fix it in one line.

3

Write a minimal reproducible example for this bug: a 200-line game crashes when the player's name is empty because name[0].upper() is called.

4

A forum answer says to use string.letters. Python says AttributeError: module 'string' has no attribute 'letters'. What happened and how do the docs help?

5

Explain why the actual mistake for a SyntaxError is sometimes on the line before the one Python marks.

Challenge

1

Use help(sorted) or the docs to find how to sort a list of strings by length, longest first, without writing a loop. Give the call and the two parameters involved.

2

A function works on your computer but fails on a classmate's with AttributeError: module 'xml.etree.ElementTree' has no attribute 'indent'. Diagnose and give two fixes.

3

Write a short checklist (5 items) that you would put at the top of your notes for solving an unknown error independently.

Check your understanding

Quiz

1.

Where in a traceback is the type of error?

2.

What does nums.sort() return?

3.

Which tool shows a function's built-in documentation inside Python?

4.

After s = "ice" and s.upper(), what is s?

5.

What is a minimal reproducible example?

6.

Why check an online answer against the official documentation?

For parents and teachers

Big idea: A4.1 asks students to work independently, using support documentation (IDE Help, tutorials, websites, user manuals) to resolve issues during software development. This lesson builds that habit with Python's help(), docs.python.org and a repeatable debugging cycle.

How to help: resist the urge to fix the bug for your teen. Ask instead: "What does the last line of the error say? What did the documentation say that function does?" Being a patient "rubber duck" is genuinely useful.

Common difficulties:

  • Reading only the first line of a traceback.
  • Changing code at random instead of forming a hypothesis.
  • Trusting a forum or AI answer without checking it against the official documentation.
  • Not retesting earlier cases after a fix.