- Lab
-
Libraries: If you want this lab, consider one of these libraries.
- Core Tech

Guided: Debugging in Python
In this Guided Code Lab, you have been given a Python program that appears to be functioning well, but in reality has a few bugs that cause it to crash or produce incorrect results. To fix this, you will be utilizing the pdb module to debug the program by identifying these issues and resolving them. While this lab is Guided, it is recommended to have a decent grasp of Python, as the bulk of this lab will be tailored towards debugging rather than explaining common Python syntax and methods.

Lab Info
Table of Contents
-
Challenge
Introduction
Overview
Welcome to the Debugging in Python lab. The program you will be working with in this lab calculates expected values for certain items in your inventory based on the values of their attributes.
Files in This Lab
There are three main Python files that you'll work with:
First is the
seedData.py
file, which populates data in thebad_items.json
anditems.json
.You can run it in the Terminal with the command at anytime to reset your inventory to a clean state:
python3 seedData.py
Second is the
calc_util.py
file, which contains most of the program's logic, including:- Calculating expected values
- Retrieving inventory data
- Adding new items.
However, it’s missing some checks and balances that cause crashes or incorrect results. You’ll debug and fix these issues during the lab.
Lastly is the
item_calculator.py
file, which contains the main logic that runs the program. Like incalc_util.py
, there are some edits you will need to make to ensure the program runs correctly.The program can be run in the Terminal with the command:
python3 item_calculator.py
Debugging and Validation
Throughout the lab, you will be using the built-in
pdb
library to debug the program and identify the causes of these errors. You will then rectify these errors to ensure the program runs as intended.
Solutions Directory
There is also a
solutions
directory that you can use to check your work. Keep in mind that your code does not need to exactly match the code in thesolutions
directory as long as you are meeting the objectives or expected behavior for the program. -
Challenge
The Program
Run the Program
Start by resetting and running the program to see its current behavior.
- In the Terminal, reset the data:
python3 seedData.py
. - Start the app:
python3 item_calculator.py
You’ll see initial item values and a prompt asking whether you want to add a new item or exit. If you choose to add a new item and enter numbers for
A
,B
,D
, andE
, the program accepts the input and adds the item.âś… Self-check: You should see a prompt to add a new item or exit, and adding numbers for
A
,B
,D
, andE
should succeed.
Observe
There are two main issues you need to address:
Unvalidated input: If you enter anything other than a number for the values, the program crashes. You should handle user input errors gracefully rather than allowing crashes.
Incorrect calculations: Expected values should never be negative. This indicates a logic error in the expected-value calculation, which you’ll fix later in the lab.
Reproduce the Crash with "Bad" Data
To surface failures consistently, point the app at a dataset that contains problematic records.
First, change the
JSON_FILE_PATH
variable at the top of thecalc_util.py
file from'data/items.json'
to'data/bad_items.json'
.Then, run the program again:
python3 item_calculator.py
. It will immediately crash, confirming that error handling is missing.âś… Self-check: Running with
bad_items.json
should crash immediately with aKeyError: 'E'
.
Your Goals for This Step
- Prevent crashes caused by invalid user input (validate and handle errors).
- Prepare to fix the expected-value calculation so it cannot produce negative results.
Outcome: By the end of the step, you can reliably reproduce the failures (using
bad_items.json
) and you understand the two categories of issues you'll fix next: input validation and calculation correctness.
Next: Now that you can reproduce the crash, continue to Step 3 – Debugging with PDB to set a breakpoint and inspect the error in action.
- In the Terminal, reset the data:
-
Challenge
Debugging with PDB
Debug the Program with PDB
To fix these errors, you will need to debug the program using Python's built-in
pdb
library.The library has already been imported for you in
item_calculator.py
, Use thepdb.set_trace()
function to set breakpoints anywhere in the code where you want to pause and inspect behavior.When the program reaches a breakpoint, the Terminal enters an interactive debugging session.
In this session, you can use
pdb
commands to:- View variable values
- Examine nearby code
- Step into functions
- Inspect the current call stack
Common
pdb
Commands:| Command | Description | |----------|--------------| |
l
| List surrounding code | |s
| Step into a function | |n
| Execute next line | |c
| Continue execution | |p
| Print a variable or expression | |q
| Quit debugging session |You'll start by debugging the first crash.
Instructions
1. Run the program again. It should crash with a `KeyError: 'E'` and display a traceback that showing which line(s) of code caused the error. 2. Check the traceback to see where the error occurs, which is at lines 16-17. 3. Add your breakpoint (`pdb.set_trace()`) right before the `item_val` variable in the `for` loop. 4. Run the program again to start the interactive session. 5. Use the command `l` to list the code around the current breakpoint line. 6. Use `s` to step into the `item_val` variable, which is returned from `calculate_item_value()`. 7. Use `p` to inspect the value of an expression. For instance, `p item["E"]` will print the value of the `"E"` key in `item`. However, doing this will print the `KeyError` that caused the crash. 8. Use `p item` instead to inspect everything inside `item`. You can see here that the `"E"` key does not even exist, which is what causes the error and crash to occur. 9. Type `exit` or `quit` to end the debugging session.
The crash occurs because the item is missing a required key.
As specified in the instructions, you used
pdb
to set a breakpoint in the code and step into the function call. In that function call, you were able to inspect variables and expressions to see what was occurring in the code, where you identified that the first item was missing a key. This was the cause for theKeyError
causing the crash.To fix this, add validation logic in the
validateItem()
function incalc_util.py
to handle missing keys.Instructions
1. In `validateItem()`, after `required_keys`, add a `for` loop to iterate through each key in `required_keys`. 2. If the `key` is not in `item.keys()`, print an error message such as: `f"Validation Error: Missing key '{key}' in item {item.get('item_id', 'unknown')}."` then return `False`. 3. Return `True` outside of the conditional. 4. In `item_calculator.py`, add an `if` conditional for `validateItem` inside the `for` loop. 5. Nest the `item_val` variable and `print` statement inside this conditional.After implementing the first portion of
validateItem()
, you can run the program again.It will still crash, but this time it will:
- Print a validation error for the first (invalid) item
- Print normally for the second (valid) item
- Crash again, this time with a
TypeError
on the third item
âś… Self-check: You should see a printed validation error for the first item, then normal output for the second, then a
TypeError
on the third.
Debug the TypeError
As you saw previously, the crash should display a traceback that details which line of code was causing the error, along with a message that specifies the error.
In this case, there is a
TypeError
that states only strings can be concatenated with strings.You’ll debug again to identify the cause.
Instructions
1. Add `pdb.set_trace()` right before `item_val`, as before. 2. Run the program. You'll see a validation error being printed. You’ll see the validation error print first, confirming it’s working. 3. Use `c` to continue until the next iteration, which should print out the value for a valid item. 4. At the next iteration starting at the `item_val` line, use the `s` command repeatedly to step into the function until you see `--Call--`. This means you've entered the function call for `calculate_item_value()`. 5. Use `n` for next line or `s` to continue stepping into the function. You can use `l` as well to check which line of code you are on, but you want to keep using `n` or `s` to move through the function until you reach the return statement at the end. 6. Use `p` to display the values of all the variables (A, B, C, X). You can view all of them with a single command by listing them separated by a comma.If displayed correctly, you should now see the values of
A
,B
,C
, andX
.Notice how only
A
is a string, while the rest are numbers. This is the source of theTypeError
being received earlier, as you can't add a string to an integer.You should modify
validateItem()
to address this just like you did for theKeyError
.
Fix the TypeError with Validation
To fix this, extend your validation logic in
validateItem()
to check for invalid data types.Instructions
1. Head to `validateItem()` again in the `calc_util.py` file. 2. Beneath the first conditional, add a second `if` conditional. 3. Check if the key is one of `"A"`, `"B"`, `"D"`, or `"E"`. 4. If it is, add another nested `if` statement to check whether the value is an integer or a float. One way to do this is `isinstance(item[key], (int, float))`. 5. If the value does not meet this requirement, print an error message of your choosing. An example could be `f"Validation Error: Invalid type for key '{key}' in item {item.get('item_id', 'unknown')}."` then return `False`.This validation will now check if each of the weighted values of an item are numbers, otherwise it will handle it by printing an error message.
âś… Self-check: The program should no longer crash on type errors; invalid numeric fields print a clear validation message.
-
Challenge
Finishing Touches
Handle Invalid User Input
Recall that there were two other issues present in the program mentioned at the start.
Although you have added validation to handle items with malformed properties, the program still crashes if you enter a non-number for any of the weights. You'll fix that now.
Instructions
1. The crash occurs due to a `ValueError` in the `add_new_item()` method in `calc_util.py`. 2. `ValueError` is raised when the function attempts to convert user input to a float. If a non-number is entered, the conversion fails. 3. To fix this, utilize a `try-except` block. Wrap the entire body of `add_new_item()` within the `try` clause. 4. For the `except` clause, printing any error message in response to the `ValueError` will suffice.
Fix the Incorrect Expected Value Logic
You may have noticed that all expected values were printed as negative.
Expected values should always be positive. While debugging
calculate_item_value()
earlier withpdb
, you saw that the value forC
was negative. This is the source of the issue.This error differs because it is a logical error rather than a runtime error, meaning that the code will run without issue because all your errors are being handled, but the results are incorrect because the actual calculations have a mistake in them.
Instructions
1. Locate the conditional statement in `calculate_item_value()` that modifies the value of `C`. 2. The condition currently always makes `C` negative. Update it so that it only runs when `D` is greater than `E` (not less than). 3. Run the program again and verify that your item values now match the `expected_value` property in the data. 4. You can find the `expected_value` property in the `bad_items.json` file in the `data` directory.âś… Self-check: Printed item values match the
expected_value
field indata/bad_items.json
.
Wrap-up
Well done!
With all these fixes, the program should now be running as intended.
You have managed to debug this program using the
pdb
library to make it fully functional.You can run it again for either json file:
python3 item_calculator.py
(bad_items
oritems
).Although you utilized some of the most commonly used commands for
pdb
for debugging, there are many more commands thatpdb
offers for debugging.You are encouraged to check them out in the
pdb
module in the official Python docs.
About the author
Real skill practice before real-world application
Hands-on Labs are real environments created by industry experts to help you learn. These environments help you gain knowledge and experience, practice without compromising your system, test without risk, destroy without fear, and let you learn from your mistakes. Hands-on Labs: practice your skills before delivering in the real world.
Learn by doing
Engage hands-on with the tools and technologies you’re learning. You pick the skill, we provide the credentials and environment.
Follow your guide
All labs have detailed instructions and objectives, guiding you through the learning process and ensuring you understand every step.
Turn time into mastery
On average, you retain 75% more of your learning if you take time to practice. Hands-on labs set you up for success to make those skills stick.