Welcome to your third lesson. In our last session, you learned how to use variables to store data and the print() function to display it. These are the fundamental actions of writing a program: storing information and showing results. Now, we'll focus on what to do when things don't go as planned.
This lesson addresses a core skill for any programmer: debugging. Your background in administration and caregiving involves a great deal of critical thinking and evaluation to solve problems, whether it's a scheduling conflict or an unexpected patient symptom. Debugging is the programming equivalent of that process: a methodical way to find the root cause of a problem and fix it. You'll learn how to interpret the error messages Python gives you and how to use the print() function as a diagnostic tool to investigate your code's behavior.
When Code Breaks: Understanding Errors
It is a simple fact of programming that you will make mistakes. Everyone does, from beginners to experts. The key is not to avoid errors entirely, but to become skilled at finding and fixing them. In Python, you'll generally encounter three types of issues:
- Syntax Errors: These are like grammatical mistakes. You've written something that doesn't follow Python's rules, so the interpreter can't even begin to run your code. A missing parenthesis or an invalid variable name are common examples.
- Runtime Errors (Exceptions): The code's syntax is correct, but an error occurs while the program is running. For instance, trying to perform a mathematical operation on a piece of text. Python will stop execution and print a message called a traceback.
- Logic Errors: This is the trickiest type. The code runs without crashing, but it produces the wrong result. The syntax is correct and the operations are valid, but the logic you've designed is flawed.
This lesson will focus on understanding runtime errors and using print() statements to uncover logic errors.
Reading the Clues: How to Interpret a Traceback
When a runtime error occurs, Python provides a traceback. It might look intimidating at first, but it's an incredibly helpful message that tells you exactly where the problem is. The key is to read it from the bottom up.
The following short video from the Python Morsels channel provides an excellent walkthrough of how to read a traceback to find and fix an error.
Traceback (most recent call last): Python's tracebacks explained
This video explains what a traceback is and demonstrates the crucial "bottom-up" reading strategy.
Please watch the entire video from start to finish. Pay close attention to how the presenter identifies the error type on the last line and then uses the lines above to find the exact location in the code.
As the video explained, the traceback gives you three key pieces of information:
- The last line tells you the type of error (e.g.,
NameError) and a specific message about what went wrong. - The lines above it show the "call stack"—the path through your code that led to the error.
- Each "stack frame" points to a specific file, a line number, and the line of code itself that was executed.
Let's dissect this with a text resource that goes into more detail.
How to Debug Common Python Errors
This article from Real Python provides a clear breakdown of a NameError traceback, labeling each part.
Please read from the beginning of the article down to the table that explains the parts of a Python traceback. Focus on the section that breaks down the traceback. This reinforces what you saw in the video.
Hands-On: Fixing a NameError
Let's apply this. Open a new Jupyter Notebook for this lesson. In a code cell, copy and paste the following code, which has a deliberate typo.
patient_name = "John Smith"
age = 45
# This line has a typo
print(f"Patient: {patient_name}, Age: {agee}")
Run the cell. You will see a NameError. Now, practice your new skill:
- Look at the last line of the traceback. It should say
NameError: name 'agee' is not defined. This is your main clue. - Look at the line above it. Python points you directly to the line of code containing
print(f"Patient: {patient_name}, Age: {agee}"). - Based on this information, you can identify that you've used an incorrect variable name (
ageeinstead ofage). Correct the typo and run the cell again to see it work.
A Tour of Common Beginner Errors
You'll encounter a few error types frequently as you start out. The video below gives a quick tour of some of the most common ones. We'll focus on the three that are most relevant to you right now.
Top 10 Most Common ERRORS In Python (And How To FIX Them)
This video from Indently demonstrates several common Python errors and how to fix them. We will focus on just a few.
Watch the following three short segments: IndentationError: This section explains errors caused by incorrect spacing, which is a type of SyntaxError unique to Python. SyntaxError: This part covers general grammatical mistakes in your code. TypeError: This clip shows what happens when you try to perform an operation on incompatible data types, like adding a number to text.
The image below provides a great visual summary of the rules for variables, data types, brackets, and indentation. Getting these right will help you avoid many common SyntaxError and NameError issues.

Hands-On: Fixing SyntaxError and TypeError
Let's fix two more broken code snippets. For each one, run the code, read the traceback, identify the error, and apply the fix.
1. SyntaxError
Copy this into a new cell. There's a missing comma in the print function.
# Before
record_id = "A-102"
record_status = "active"
print("Record ID:" record_id, "Status:", record_status)
2. TypeError
Copy this into another cell. It tries to add a string and a number.
# Before
initial_reading = "50" # This is a string, not a number
increase = 10
new_reading = initial_reading + increase
print(f"New reading: {new_reading}")
Hint for the fix: You need to convert the initial_reading string into a number before you can add increase to it. You can do this with int(), like this: int(initial_reading).
Uncovering Logic Errors with print()
Sometimes your code runs perfectly but gives you the wrong answer. This is a logic error. Python can't tell you what's wrong because you haven't broken any of its rules; you've just given it a flawed set of instructions.
This is where your print() function becomes a powerful debugging tool. By strategically placing print() statements, you can inspect the values of your variables at different points in your code to see where your logic goes wrong.
Let's see this in action. Imagine you are calculating the total cost of an order. There are 3 items at $20 each, and a flat $5 shipping fee. The total should be .
Copy this code into a new cell. It contains a logic error.
num_items = 3
item_price = 20
shipping_fee = 5
# Flawed calculation due to order of operations
total_cost = num_items * item_price + shipping_fee
print(f"The incorrect total cost is: ${total_cost}")
When you run this, it prints $65. Wait... in this simple case, the order of operations works out. Let's make it more obvious.
Let's change the calculation:
num_items = 3
item_price = 20
shipping_fee = 5
# Flawed calculation due to order of operations
total_cost = shipping_fee + item_price * num_items
print(f"The incorrect total cost is: ${total_cost}")
The result is still correct. The problem with order of operations is more subtle. Let's try another flawed calculation. The goal is to calculate the total price including a discount.
# Goal: Calculate the price of 3 items at $20 each, with a $5 discount on the total.
# Expected result: (3 * 20) - 5 = $55
num_items = 3
item_price = 20
discount = 5
# Flawed calculation
total_cost = num_items * item_price - discount
print(f"The incorrect total cost is: ${total_cost}")
Again, this works. Let's try another example.
Goal: average of three numbers.
# Goal: Calculate the average of three exam scores.
score1 = 80
score2 = 90
score3 = 95
# Flawed logic
average_score = score1 + score2 + score3 / 3
print(f"Average score: {average_score}")
Run this code. The output is 201.66..., which is clearly wrong. The average of 80, 90, and 95 should be around 88.
Let's use print() to investigate. We can print the intermediate parts of our calculation to see what Python is doing.
score1 = 80
score2 = 90
score3 = 95
# Let's inspect the parts of the calculation
print(f"The value of score3 / 3 is: {score3 / 3}")
print(f"The value of score1 + score2 is: {score1 + score2}")
# Flawed logic
average_score = score1 + score2 + score3 / 3
print(f"Final calculated average: {average_score}")
When you run this, you'll see that Python calculates score3 / 3 first due to the mathematical order of operations. It calculates 95 / 3 and then adds 80 and 90 to that result. Our print statements make this visible.
To fix the logic, we need to use parentheses to force the addition to happen first:
# Correct logic
average_score = (score1 + score2 + score3) / 3
print(f"Correct average score: {average_score}")
Now, the result is 88.33..., which is correct. This process of using print() to check variable states is one of the most fundamental and useful debugging techniques you will ever learn.
To see this same strategy applied in a more complex scenario, you can review the Real Python article again.
How to Debug Common Python Errors
This section of the article demonstrates using print() to solve a logic error in a function. The code itself is more advanced than what you know, but the strategy is exactly what we just practiced.
Read the section titled "Debugging With print()". Don't worry about understanding every line of the palindrome code; focus on how the author inserts print() statements to check the value of variables at each step to find the problem.
Conclusion
You've now learned the essential skill of debugging. While it can be frustrating to run into errors, you now have a systematic way to approach them. Think of it as a puzzle to be solved rather than a barrier.
Here are the main takeaways from this lesson:
- Errors are a normal part of programming. Learning to debug is a critical skill.
- Tracebacks are your friend. Read them from the bottom up to find the error type, message, and location.
- The most common errors you'll see initially are
NameError(typos),SyntaxError(grammar), andTypeError(mismatched data types). - For logic errors where the code runs but gives the wrong output, use the
print()function as a diagnostic tool to inspect variable values at different stages of your program.
In our next lesson, you will learn how to write conditional statements (if/elif/else). This will allow your programs to make decisions and follow different paths based on the data they are working with. As your code becomes more complex, the debugging skills you learned today will become even more valuable.