Debugging Techniques and Reading Error Messages
The Python interpreter recovers from errors and returns a prompt; a script terminates immediately with a traceback.
Try it: Reading a Traceback
How to read a Python traceback: the last line names the error type and message, the frame at the bottom is where Python discovered the problem, each frame above is a call that led there, and the root cause is often earlier than the reported line, in the data passed down the calls.
How it works
- Execution runs line by line; each function call pushes a new frame onto the call stack.
- When an operation fails (words[0] on an empty list, 'a' + 5, int('x9'), d['missing'], x / 0, an undefined name, None.upper()), Python raises an exception at that line.
- With no try/except, the exception leaves the frame and returns to the caller at the line that made the call; that call becomes the next entry above in the traceback.
- CPython prints "Traceback (most recent call last):", one File/line/function entry per frame from the outermost call down to the failing line, with ^^^ / ~~~^^^ markers under the failing expression, then "Type: message".
- Read it from the bottom (what failed and where) upwards (how execution got there), then look for where the bad value came from: that is the cause; the reported line is the symptom.
Default run (20 steps): First words: the value on the last line is "". Press Play to run it and watch for the error. … Uncaught: CPython prints the traceback and stops. Read it from the bottom: IndexError: list index out of range was discovered at line 3 in first_word; the lines above show how execution got there.
Simplified: The lab's own small Python interpreter runs fixed, hand-written programs (you pick the program, the fix and a value; your text is never executed). Every program the lab can show was run in CPython 3.12 and the lab reproduces its output, its traceback text and its line-by-line trace. Seven short programs; you choose the value on the last line, which makes the error appear or disappear.
Loading the simulation…
Two Ways Python Runs
An error does not have the same visible effect in every Python setting. When you type commands directly into the Python interpreter, Python reports the error and gives you a new prompt. You can then try another command. When you run a script from a file, an error stops the script immediately and Python prints a traceback. This difference is the starting point for reading error messages effectively.
What ValueError Means
A ValueError occurs when a function receives an argument of the correct type but an inappropriate value. A common example is passing a string to int() or float() when the string contains letters or other characters that do not represent a valid number.
The important distinction is between type and value. The conversion function receives a string, so the argument has the kind of input the function can examine. However, the contents of that string are not suitable for the requested numeric conversion. For example, int('hello') raises a ValueError because the string does not represent an integer.
Following Script Termination
In a script, a ValueError or another exception stops execution immediately when the error is not handled. Statements after the failing statement are not executed. Python prints a traceback instead, giving a detailed report of where the error occurred and the sequence of calls that led to it.
The Fahrenheit Conversion Failure
A script reads a Fahrenheit temperature and assigns the converted input with fahr = float(inp). The input is the string 'fred'. What happens?
- 1Conversion begins
The script passes the string 'fred' to
float(). - 2Conversion fails
The string has the required string form of an argument, but its contents do not represent a valid floating-point number. Python raises a
ValueError. - 3Traceback appears
The traceback identifies the file
fahren.py, line 2, the statement fahr =float(inp), and the message that 'fred' could not be converted to a float. - 4Later statements stop
The calculation on line 3 and the print on line 4 are not executed because the script terminates at the exception.
The script stops at the conversion statement and prints a traceback instead of producing the temperature result.
Reading the Traceback
A traceback is a roadmap for locating a failure. It presents the chain of calls that led to the exception, narrowing the investigation to the statement where the error occurred. In the Fahrenheit example, the traceback begins with the heading Traceback (most recent call last):. The entry File "fahren.py", line 2, in <module> identifies the file, line number, and top-level location. Python then displays fahr = float(inp), followed by ValueError: could not convert string to float: 'fred'.
- Start with the exception name, such as
ValueError, to understand the category of failure. - Use the file name and line number to locate the relevant part of the script.
- Read the displayed statement to identify the operation that failed.
- Read the final exception message for the specific value or condition Python rejected.
Interactive Recovery and Script Repair
Interactive recovery lets you continue experimenting after an error: read the message, return to the new prompt, and try a different command or value. A failed script requires a different response. Read the traceback, locate the failing statement, change the program or its input, and then run the script again. The interpreter's new prompt is not evidence that the original command succeeded; it only means the interactive session is ready for another command.
Common mistake Assuming that an error in the interpreter ends the whole session.
What it looks likeA ValueError is displayed, followed by a new prompt.
Why it failsThe interactive interpreter recovers and allows another command.
Do this insteadTreat the error message as feedback, then inspect or replace the command before trying again.
Common mistake Assuming that later script statements will run after a ValueError.
What it looks likeA conversion fails before the calculation and print statements.
Why it failsAn unhandled exception stops the script immediately.
Do this insteadUse the traceback to locate the failing statement and remember that later statements were not executed.
Common mistake Reading only the final exception name and ignoring the traceback location.
What it looks likeNoticing ValueError but overlooking fahren.py, line 2 and fahr = float(inp).
Why it failsThe exception name describes the category, while the file, line, and statement identify where to investigate.
Do this insteadRead the traceback from its context through the exact statement and final message.
Practice
A script attempts to convert the string 'fred' with float(). Identify the exception category, the operation that failed, and whether statements after the conversion execute.
Hints
- Ask whether the string contents represent a valid floating-point number.
- Look for the conversion operation rather than the later calculation.
- Apply the script rule for an unhandled exception.
Key Takeaways
- 1The interactive interpreter reports an error and returns a prompt, allowing another command.
- 2A script terminates immediately when an unhandled exception occurs and prints a traceback.
- 3A
ValueErrormeans that a function received an argument of the correct type but an inappropriate value. - 4A traceback connects the exception to the file, line number, failed statement, and sequence of calls.
- 5Reading tracebacks is the foundation for repairing programs and learning to handle errors with try and except.
At a glance
- The interpreter recovers by showing an error and returning a prompt, while a script stops with a traceback.
ValueErrorcommonly appears whenint()orfloat()receives a string whose contents cannot represent the requested number.- A traceback identifies the path to failure through its file, line number, statement, exception type, and message.
- After a script fails, use the traceback to locate the problem, change the program or input, and run it again.