Skip to content
PythonModules, Files, and Errorsbeginner25 min read

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

Find a logical bug
python
price = 100
quantity = 3
 
# Intended: calculate the total cost.
total = price + quantity
print(total)
Output
103

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

An error message is evidence, not always the complete explanation. Debugging means using the evidence, code, and expected behavior to identify the actual cause.

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

Debug an incorrect total
python
def calculate_total(prices):
total = 0
for price in prices:
total = price
return total
 
print(calculate_total([10, 20, 30]))
Output
30

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

Before changing code, write down the expected result and the actual result. The difference often helps narrow the search for the bug.

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

Inspect a running total
python
numbers = [2, 4, 6]
total = 0
 
for number in numbers:
print('Before:', total)
total += number
print('After:', total)
 
print('Final total:', total)
Output
Before: 0 After: 2 Before: 2 After: 6 Before: 6 After: 12 Final total: 12

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

A print statement reveals a value at a particular point in execution. It does not automatically explain why that value was produced, so inspect the statements that led to it.

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

Pause and inspect a variable
python
def calculate_total(price, quantity):
total = price * quantity
breakpoint()
return total
 
print(calculate_total(50, 3))
Output
150

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

Use breakpoints when you need to inspect state without adding many temporary print statements. Remove or disable intentional debugging stops before delivering a program that should run unattended.

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

An assertion that succeeds
python
total = 3 + 4
assert total == 7
print('Check passed')
Output
Check passed

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

Assertions can be removed when Python runs with optimization. Never rely on assert to validate untrusted input, enforce permissions, or guarantee that essential application checks always execute.

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

Check a calculated result
python
def calculate_area(width, height):
return width * height
 
area = calculate_area(5, 4)
assert area == 20, 'Area calculation is incorrect.'
print('Area:', area)
Output
Area: 20

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

Use assert to check an assumption that should already be true. Use if statements, exceptions, or other explicit validation logic to handle conditions that can occur during normal use.

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

Test several cases
python
def add(a, b):
return a + b
 
assert add(2, 3) == 5
assert add(0, 0) == 0
assert add(-2, 2) == 0
 
print('All checks passed')
Output
All checks passed

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

When you fix a bug, rerun the failing test and related tests. This helps confirm that the correction addresses the cause rather than merely changing the observed output.

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.

Incorrect Approach
script.py
python
Assuming that a program is correct because it runs without raising an exception.
Correct Solution
script.py
python
Compare its actual behavior with the requirement. Logical bugs can produce incorrect results without causing exceptions.

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.

Incorrect Approach
script.py
python
Changing multiple unrelated statements before identifying the cause.
Correct Solution
script.py
python
Reproduce the problem, isolate the relevant operation, inspect its values, form a hypothesis, and make a focused correction.

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.

Incorrect Approach
script.py
python
Printing values without knowing what they should be.
Correct Solution
script.py
python
Write down the expected value or condition first, then compare it with the inspected value.

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.

Incorrect Approach
script.py
python
Assuming a successful assert prints True or a success message.
Correct Solution
script.py
python
A successful assertion produces no output by itself. Only an explicit print statement displays a message.

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.

Incorrect Approach
script.py
python
Assuming assert always runs.
Correct Solution
script.py
python
Python can disable assertions under optimization. Do not put essential validation or required side effects inside assert expressions.

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.

Incorrect Approach
script.py
python
Using assert to reject invalid user input.
Correct Solution
script.py
python
Use explicit conditional checks and suitable error handling for externally supplied values or conditions the program must always enforce.

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.

Incorrect Approach
script.py
python
Testing only the input that originally exposed the bug.
Correct Solution
script.py
python
Retest the failing case, an ordinary case, and relevant boundary cases to check for regressions.

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.

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?
Answer:
Debugging is the process of finding and fixing defects. I reproduce the problem, isolate the relevant code, inspect variables and control flow, form a hypothesis about the cause, make a focused correction, and retest the failing case along with normal and boundary cases.
Q2:What is the difference between a syntax error, a runtime exception, and a logical bug?
Answer:
A syntax error prevents Python from parsing the code. A runtime exception is raised during execution when an operation cannot proceed normally. A logical bug causes incorrect behavior even though the code may execute without an exception.
Q3:What is an assertion in Python?
Answer:
An assertion checks a condition that the developer expects to be true. If the condition is false and assertions are enabled, Python raises AssertionError. A successful assertion produces no output by itself.
Q4:When should you use assert, and when should you avoid it?
Answer:
Use assertions to check internal assumptions and invariants during development. Avoid relying on them for user-input validation, access control, security requirements, or any check that must always execute, because assertions can be disabled under optimization.
Q5:How can print statements help with debugging?
Answer:
Print statements expose variable values and intermediate results at selected points in execution. They can help reveal incorrect calculations or unexpected branches. Descriptive labels make the output easier to interpret, and temporary diagnostic statements should be removed when no longer needed.
Q6:What is a breakpoint?
Answer:
A breakpoint pauses execution at a selected location in a debugging session. The developer can inspect variables, follow control flow, and step through statements to investigate the cause of incorrect behavior.
Q7:Why should you test edge cases after fixing a bug?
Answer:
A fix may work for the original input but fail for zero, negative values, empty collections, or other relevant cases. Testing the failing case and related cases helps verify the intended behavior and detect regressions.

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.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: