Debugging & TestingGet Certified
What Is Debugging?
Debugging is the process of finding and fixing problems in your code. Problems can be syntax errors that stop the program from running, runtime exceptions that crash it, or logic errors that produce the wrong answer. Good debugging habits save time and make your programs more reliable.
Effective debugging begins with understanding what the program should do and comparing that expectation with what it actually does. Work through the code step by step instead of changing several lines at once. A clear description of the problem helps narrow down its cause. Once you identify the issue, make a focused correction and run the program again.
- Read the error message carefully — it usually points to the file and line number.
- Use
print()statements to inspect the values of variables at key points. - Test small pieces of code with known inputs and expected outputs.
- Fix one problem at a time and re-test after each change.
Reading Error Messages
Python error messages provide useful clues about what went wrong and where to begin investigating. A traceback lists the sequence of function calls that led to the error, with the most recent call shown near the bottom. Check the exception name and the indicated line, then review the values and operations used there. Understanding these details is more useful than simply copying the error message into a search.
When Python raises an exception it prints a traceback. Learning to read that traceback is the first debugging skill. The examples below catch the error so you can still see a clear message.
Try It: Catching a NameError
print("Maya in Seattle is checking a variable.")
score = 95
try:
print("The score is", scroe)
except NameError as err:
print("NameError caught:", err)
print("Did you mean the variable 'score'?")
print("Program continues.")Try It: Catching a TypeError
print("Jordan in Austin is combining values.")
age = 16
message = " years old"
try:
print(age + message)
except TypeError as err:
print("TypeError caught:", err)
print("Correct way:")
print(str(age) + message)Using print() to Debug
The print() function can reveal how data changes while a program is running. Place temporary print statements before and after calculations, conditions, or function calls to inspect important values. Compare the displayed results with the values you expect at each step. Remove or replace these temporary statements when debugging is complete so normal program output stays clear.
When the program runs but gives the wrong answer, temporary print statements are the simplest way to see what the variables actually contain.
Try It: Inspecting Intermediate Values
print("Taylor in Chicago is checking a discount.")
price = 80
discount_rate = 0.15
print("Price before discount:", price)
discount = price * discount_rate
print("Discount amount:", discount)
final_price = price - discount
print("Final price:", final_price)Finding Logic Errors
A logic error can be difficult to notice because Python may execute the program without displaying an exception. The best approach is to compare actual results with expected results using simple test cases. Pay particular attention to loop boundaries, conditions, and calculations that depend on multiple values. Testing edge cases, such as zero or the first and last item, can reveal mistakes that ordinary inputs may miss.
Logic errors do not raise exceptions; the program runs but produces incorrect results. Careful testing with known inputs is the best way to discover them.
Try It: Off-by-One Mistake
print("Riley in Denver is summing numbers.")
total = 0
for n in range(1, 5):
print("Adding", n)
total = total + n
print("Sum is", total)
print("Expected sum of 1 through 5 is 15.")Try It: Corrected Version
print("Riley in Denver fixed the range.")
total = 0
for n in range(1, 6):
print("Adding", n)
total = total + n
print("Sum is", total)Using assert for Quick Checks
Assertions are useful when a particular condition must be true for the program to continue correctly. They make assumptions visible and help identify unexpected values during development. If an assertion fails, Python raises an AssertionError and displays the optional message supplied with it. Use assertions for internal checks rather than for validating normal user input or handling expected runtime errors.
The assert statement tests a condition and raises AssertionError if the condition is false. It is useful for catching mistakes early during development.
Try It: Assertion That Passes
print("Casey in Boston is checking rectangle area.")
width = 4
height = 6
area = width * height
print("Calculated area:", area)
assert area > 0, "Area must be positive"
print("Assertion passed. Area is valid.")Testing a Small Function
A function should be checked with more than one input so that its behavior is not judged by a single successful result. Include typical values, boundary values, and inputs that exercise different branches of the function. Decide what each call should return before running the test, then compare the actual output with that expectation. This simple process helps catch incorrect conditions and calculation mistakes early.
Writing a function and then calling it with several known inputs is a practical way to test that the logic is correct.
Try It: Testing a Grade Function
print("Avery in Portland is testing letter grades.")
def letter_grade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
else:
return "F"
print("95 →", letter_grade(95))
print("82 →", letter_grade(82))
print("70 →", letter_grade(70))
print("55 →", letter_grade(55))Try It: Finding and Fixing a Calculation Mistake
print("Quinn in Minneapolis is averaging scores.")
score1 = 88
score2 = 92
score3 = 79
print("Scores:", score1, score2, score3)
buggy = (score1 + score2 + score3) / 2
print("Buggy average (divided by 2):", buggy)
correct = (score1 + score2 + score3) / 3
print("Correct average (divided by 3):", round(correct, 1))Practical Debugging Tips
A consistent debugging routine makes problems easier to isolate and fix. First reproduce the issue, then narrow the search to the smallest section of code that could cause it. Use readable variable names and small functions so that each part of the program has a clear responsibility. After making a change, rerun the relevant tests to check that the fix works and has not introduced another problem.
- Read the full traceback from the bottom up; the last line usually shows the exact problem.
- Add print statements before and after suspicious lines to see how values change.
- Test with simple, known inputs whose correct answers you can calculate by hand.
- Fix the first error you find, then run the program again; later errors may disappear.
- When a function misbehaves, call it with several different arguments and compare the outputs.
- Keep the code you are testing small; large blocks make it harder to locate the mistake.
Key Takeaways
Debugging and testing are essential parts of writing dependable Python programs. Error messages and tracebacks help locate exceptions, while print statements can expose unexpected intermediate values. Logic errors require careful comparison between expected and actual results, and assertions can check important assumptions during development. Regularly testing functions with varied inputs helps you find problems before they affect larger programs.
- Debugging is the process of locating and correcting errors in code.
- Tracebacks tell you the type of error and the line where it occurred.
- print() statements are a simple and effective way to inspect variable values.
- Logic errors produce wrong answers without raising exceptions; testing reveals them.
- assert lets you state assumptions and stop the program when they are violated.
- Testing a function with multiple known inputs builds confidence that it works correctly.
Frequently Asked Questions
The questions below cover common issues that beginners encounter when debugging and testing Python code. They explain how to interpret errors, investigate incorrect results, and choose simple checks during development. Use the answers as a quick reference when a program behaves differently from what you expected. Practicing these techniques will make troubleshooting more systematic and less frustrating.
What is the difference between a syntax error and a logic error?
A syntax error prevents the program from running at all because the code violates Python’s grammar rules. A logic error lets the program run but produces incorrect results. Syntax errors are reported immediately; logic errors must be discovered through testing.
How do I read a Python traceback?
Start at the bottom of the traceback. The last line names the exception type and a short message. The lines above it show the call stack, with the most recent call at the bottom. The file name and line number point to the exact location of the problem.
When should I use assert?
Use assert during development to check conditions that should always be true. If the condition fails, you know something is wrong in the surrounding logic. Assertions can be disabled in optimized production runs, so do not rely on them for normal error handling.
Is it okay to leave print statements in finished code?
Temporary print statements used for debugging should be removed (or turned into proper logging) before the code is considered finished. Leaving them in can clutter the output and make the program harder to use.
What is an off-by-one error?
An off-by-one error occurs when a loop or index is one step too short or too long— for example using range(1, 5) when you meant to include the number 5. Printing the values that are actually processed is the fastest way to spot it.
How can I test a function without a testing framework?
Call the function several times with different inputs whose expected results you already know. Print both the input and the returned value so you can compare them at a glance. This manual approach works well for small functions while you are learning.
Why does my program give the wrong answer but show no error?
That is a classic logic error. The code is syntactically valid and no exception is raised, yet the calculations or decisions are incorrect. Insert print statements to examine intermediate values, or test the code with simple inputs whose correct answers you can compute by hand.
What should I do first when I see an error message?
Read the entire message, especially the exception type and the line number. Look at that line and the few lines above it. Many errors are simple typos, missing parentheses, or incorrect variable names that become obvious once you know where to look.