Debugging Techniques and Reading Error Messages
The Python interpreter recovers from errors and returns a prompt; a script terminates immediately with a traceback.
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?
Conversion begins: The script passes the string 'fred' to float().
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.
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.
Later 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.
Assuming that an error in the interpreter ends the whole session.
The interactive interpreter recovers and allows another command.
Fix:
Treat the error message as feedback, then inspect or replace the command before trying again.Assuming that later script statements will run after a ValueError.
An unhandled exception stops the script immediately.
Fix:
Use the traceback to locate the failing statement and remember that later statements were not executed.Reading only the final exception name and ignoring the traceback location.
The exception name describes the category, while the file, line, and statement identify where to investigate.
Fix:
Read 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
- The interactive interpreter reports an error and returns a prompt, allowing another command.
- A script terminates immediately when an unhandled exception occurs and prints a traceback.
- A ValueError means that a function received an argument of the correct type but an inappropriate value.
- A traceback connects the exception to the file, line number, failed statement, and sequence of calls.
- Reading tracebacks is the foundation for repairing programs and learning to handle errors with try and except.
Key Takeaways
- 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.