Concepts / Debugging Techniques and Reading Error Messages

Debugging Techniques and Reading Error Messages

The Python interpreter recovers from errors and returns a prompt; a script terminates immediately with a traceback.

  • Programming
Interactive lab

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

  1. Execution runs line by line; each function call pushes a new frame onto the call stack.
  2. 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.
  3. 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.
  4. 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".
  5. 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.

Educational simulation

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.

InterpreterError messageNew promptPython scriptErrorTracebackTerminationerrorreturnserrorprintsends execution
What happens next after an error occurs in the interactive interpreter compared with a Python script?

What ValueError Means

Definition

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.

python
'hello'string valueint()integer conversionValueErrorinvalid valuereceivedcontents unsuitable
What happens when Python tries to convert a value into a type that its contents cannot represent?

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.

Inputtemperature textfloat(inp)ValueErrorTracebackTerminationCalculationnot executedOutputnot executedpasses textinvalid valuereports locationends scriptskipsskips
How does an error cause a script to stop, and how does the traceback show where execution failed?
Worked example

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?

  1. 1
    Conversion begins

    The script passes the string 'fred' to float().

  2. 2
    Conversion 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.

  3. 3
    Traceback 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.

  4. 4
    Later statements stop

    The calculation on line 3 and the print on line 4 are not executed because the script terminates at the exception.

Result

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'.

Tracebackcall sequencefahren.pyline 2fahr = float(inp)failed statementValueErrorinvalid conversionnarrows toshowsproduces
How are the file name, line number, code line, and exception message connected in a traceback?
  • 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 like

    A ValueError is displayed, followed by a new prompt.

    Why it fails

    The interactive interpreter recovers and allows another command.

    Do this instead

    Treat 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 like

    A conversion fails before the calculation and print statements.

    Why it fails

    An unhandled exception stops the script immediately.

    Do this instead

    Use 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 like

    Noticing ValueError but overlooking fahren.py, line 2 and fahr = float(inp).

    Why it fails

    The exception name describes the category, while the file, line, and statement identify where to investigate.

    Do this instead

    Read the traceback from its context through the exact statement and final message.

Practice

EASY

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

  1. 1
    The interactive interpreter reports an error and returns a prompt, allowing another command.
  2. 2
    A script terminates immediately when an unhandled exception occurs and prints a traceback.
  3. 3
    A ValueError means that a function received an argument of the correct type but an inappropriate value.
  4. 4
    A traceback connects the exception to the file, line number, failed statement, and sequence of calls.
  5. 5
    Reading 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.
  • ValueError commonly appears when int() or float() 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.

Related concepts

More concepts starting with D