Debugging and Assertions
Find and fix bugs systematically, inspect program state, use assertions correctly, and verify solutions with meaningful tests.
In this lesson, you will learn
- ✓Explain what debugging is and distinguish a bug from an exception message.
- ✓Use a systematic process to reproduce, isolate, inspect, fix, and retest a defect.
- ✓Inspect variable values and execution flow using print statements and a debugger.
- ✓Explain how assert evaluates a condition and when it raises AssertionError.
- ✓Use assertions to check internal assumptions without replacing input validation.
- ✓Predict program output and test normal, boundary, and invalid cases.
1. What is debugging?
Debugging is the process of identifying, understanding, and fixing defects in a program. A bug can cause an exception, produce an incorrect answer, skip required work, or behave incorrectly only for particular inputs.
A syntax error prevents Python from parsing the affected code. An unhandled exception interrupts normal execution. A logical bug can be more difficult to notice because the program may run successfully while returning an incorrect result.
A useful debugging process is to reproduce the problem, isolate the smallest part of the program that causes it, inspect relevant values and control flow, fix the underlying cause, and retest the program. Changing code randomly without understanding the failure can introduce additional bugs.
Find a logical bug
The program executes without raising an exception. However, the intended calculation is price multiplied by quantity, not price plus quantity. The output 103 is therefore evidence of a logical bug. The correct operation is total = price * quantity, which produces 300.
Note
2. Follow a systematic debugging workflow
Step 1: Reproduce the problem. Find an input and sequence of actions that reliably produce the incorrect result.
Step 2: Isolate the cause. Reduce the example or narrow your investigation to the function, condition, or calculation that appears responsible.
Step 3: Inspect the program. Check the values of variables, the order in which statements execute, and whether conditions behave as expected. A traceback is useful when an exception occurs.
Step 4: Form a hypothesis. Explain which operation or assumption appears incorrect and why it would produce the observed behavior.
Step 5: Make a focused correction. Change the smallest relevant part of the code rather than rewriting unrelated logic.
Step 6: Retest. Verify the original failing case, at least one ordinary case, and relevant boundary cases. Check that the fix has not broken previously working behavior.
Debug an incorrect total
The requirement is to calculate the sum of all prices, so the expected result is 60. The actual result is 30 because total = price replaces the running total on every iteration. The last loop iteration overwrites the previous value, leaving total equal to 30. The likely cause is the assignment inside the loop. A running sum should add each price to the existing total.
Note
3. Inspect values with print statements
One of the simplest debugging techniques is to print a variable at a useful point in the program. This lets you inspect the value that Python has computed so far.
Place temporary print statements before and after a suspicious calculation, inside a loop, or around a conditional branch. Include a descriptive label so you know which value is being displayed.
Print debugging is useful for small programs, but too many print statements can make the output confusing. Remove temporary diagnostics when they are no longer needed, or use a debugger when you need to inspect execution more precisely.
Inspect a running total
The first print displays the total before adding the current number. The second print displays the total after the addition. Each iteration shows how the running total changes. If an intermediate value is unexpected, inspect the corresponding input and operation rather than assuming the final result is the only problem.
Note
4. Use a debugger and breakpoints
A debugger is a tool that lets you pause program execution and inspect the program's state. A breakpoint marks a location where execution should pause when running under a debugger.
At a breakpoint, you can inspect local variables, step through statements, follow function calls, and observe which branches execute. Step Over generally executes the current line without entering a called function. Step Into enters a function call when possible. Step Out continues until the current function returns.
The exact controls depend on the editor or debugger. In Python, the built-in breakpoint() function can pause execution and enter the configured debugger, commonly the built-in debugger in a standard interactive setup. You can then inspect values and continue execution.
Pause and inspect a variable
The function calculates total as 150. When run in a normal environment with the standard debugger configured, breakpoint() pauses execution before the return statement. At the pause, inspect total to confirm that it is 150, then continue execution. After continuing, the function returns 150 and print displays it. The pause and debugger prompts are interactive debugger behavior, not part of the program's ordinary printed output.
Note
5. What is an assertion?
An assertion checks whether a condition is true at a particular point in a program. In Python, the basic syntax is assert condition. If the condition is true, execution continues and no output is produced by the assertion itself. If the condition is false, Python raises AssertionError.
Assertions are useful for documenting and checking assumptions made by the program or developer. For example, a function that expects a list of nonnegative values might assert that every value is nonnegative after the function's input requirements have been established.
An assertion does not automatically fix a problem or print a custom message. It checks a condition and signals when the condition is false. You can provide an optional message using assert condition, message.
Assertions are primarily intended for internal correctness checks during development. They can be disabled when Python runs with optimization, such as with the -O command-line option. Do not use assertions as the only protection for user input, security checks, or other conditions that must always be enforced.
An assertion that succeeds
Python calculates total as 7. The condition total == 7 evaluates to True, so the assertion succeeds. The assertion itself displays no output. Execution continues and print displays Check passed.
Caution
6. Write useful assertions
A useful assertion checks one clear assumption that should hold at that point in the program. It should help explain the expected state of the program and reveal a defect if the assumption is violated.
For example, after calculating a total from a known test list, you can assert that the result matches the expected sum. Inside a function, you can assert an internal invariant that the implementation is responsible for preserving.
Do not use assertions for normal decisions that a program is expected to handle. If a user may enter an invalid value, use an if statement to check that value and display an appropriate message or raise a deliberate exception. An assertion failure usually signals a violated developer assumption, not a routine user-facing validation result.
Avoid putting required side effects inside an assertion expression. Because assertions can be disabled, an expression inside assert may not be evaluated at all when optimization is enabled.
Check a calculated result
The function multiplies width by height and returns 20. The assertion checks the result against the expected value. Because the condition is true, no AssertionError is raised. The final print statement displays Area: 20. This is a useful check for a known example during development, but one successful test does not prove that every possible input is handled correctly.
Note
7. Combine debugging with testing
A single successful example is not enough to establish that a program works. Once a bug is fixed, test the specific case that failed and then try representative inputs that exercise other paths through the code.
For a function that adds numbers, test positive values, zero, negative values, and an empty collection if the function is intended to accept one. For a function that divides, test a normal nonzero divisor and the behavior required when the divisor is zero.
Assertions can be used in simple development checks, while dedicated test frameworks such as unittest or pytest can organize repeatable tests. A test should compare the actual behavior with a clearly defined expectation.
Keep the requirement separate from the implementation. If a test fails, first verify that the expected result matches the requirement, then inspect the implementation and the input used by the test.
Test several cases
The first assertion checks addition of two positive numbers. The second checks the zero case. The third checks addition of a negative and a positive number. If any assertion fails, Python raises AssertionError and the final print is skipped. If all three assertions succeed, the program prints All checks passed. These checks illustrate several cases; a real test suite should reflect the full requirements of the function.
Note
Common pitfalls to avoid
Real debugging lessons and exact syntax contrasts to avoid runtime bugs
#1 Assuming that a program is correct because it runs without raising an exception.
Why it happens: A program can complete without an exception while still producing incorrect results, so compare behavior with expected outcomes.
Key takeaway: Compare its actual behavior with the requirement. Logical bugs can produce incorrect results without causing exceptions.
#2 Changing multiple unrelated statements before identifying the cause.
Why it happens: Changing several unrelated lines at once makes it difficult to identify which change affected the bug; isolate and test one cause at a time.
Key takeaway: Reproduce the problem, isolate the relevant operation, inspect its values, form a hypothesis, and make a focused correction.
#3 Printing values without knowing what they should be.
Why it happens: Debug output is useful only when compared with expected values or invariants; otherwise it may not reveal what is wrong.
Key takeaway: Write down the expected value or condition first, then compare it with the inspected value.
#4 Assuming a successful assert prints True or a success message.
Why it happens: A successful assert continues silently; it raises AssertionError only when its condition is false.
Key takeaway: A successful assertion produces no output by itself. Only an explicit print statement displays a message.
#5 Assuming assert always runs.
Why it happens: Assertions can be removed when Python runs with optimization enabled, so they should not enforce required runtime validation.
Key takeaway: Python can disable assertions under optimization. Do not put essential validation or required side effects inside assert expressions.
#6 Using assert to reject invalid user input.
Why it happens: Assertions express developer assumptions and may be disabled; validate untrusted user input with explicit conditions and exceptions instead.
Key takeaway: Use explicit conditional checks and suitable error handling for externally supplied values or conditions the program must always enforce.
#7 Testing only the input that originally exposed the bug.
Why it happens: A fix can solve one example while breaking another; add regression tests and cover boundary and representative inputs.
Key takeaway: Retest the failing case, an ordinary case, and relevant boundary cases to check for regressions.
Ready for hands-on challenges?
Test your skills with shuffled coding challenges in the Practice Arena.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:What is debugging, and what steps do you follow to debug a program?
Q2:What is the difference between a syntax error, a runtime exception, and a logical bug?
Q3:What is an assertion in Python?
Q4:When should you use assert, and when should you avoid it?
Q5:How can print statements help with debugging?
Q6:What is a breakpoint?
Q7:Why should you test edge cases after fixing a bug?
Key takeaways
- Debugging means identifying the cause of incorrect behavior, correcting it, and verifying the correction.
- Reproduce, isolate, inspect, fix, and retest instead of changing code randomly.
- Print statements and breakpoints help inspect variable values and execution flow.
- A successful assert produces no output; a failed assertion raises AssertionError when assertions are enabled.
- Assertions are useful for internal assumptions, not as the only way to validate external input.
- Python can disable assertions when optimization is enabled, so never put essential side effects or mandatory checks inside assert expressions.
- Test the original failing case, normal inputs, and relevant boundary cases after making a change.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: