Debugging begins by comparing expected output with actual output. You can often find the problem before using advanced tools.
Understanding the Concept
Write down what the program should display for a known input. Run it and compare. If the result differs, examine each intermediate value rather than changing the final print line at random. Print short labels with variables so you can see whether an incorrect value came from input, calculation, or formatting. Once the error is understood, remove temporary diagnostics or replace them with proper tests.
When and Why You Would Use This
The example below has an intentional logic error: it uses subtraction where a discount should be applied as a percentage. The script runs successfully, so there is no traceback to guide you.
Practical Example
original_price = 100
discount_percentage = 20
incorrect_final_price = original_price - discount_percentage
print("Final price:", incorrect_final_price)
Understanding the Example
For this specific input, the result happens to be 80, which looks correct. Try an original price of 50: the program prints 30, but a 20 percent discount should produce 40. This demonstrates why testing only one convenient input is insufficient.
Example Output
Final price: 80
Try It Yourself
Correct the formula using original_price * (1 - discount_percentage / 100) and test with original prices 50 and 100.
Common Beginner Mistakes
- Assuming a program with no exception must be correct.
- Testing only one case that happens to conceal a formula error.
- Adding debug output without labels and then misreading the values.
Key Takeaways
- Compare actual output against expected output for multiple cases.
- Logic errors can exist without Python exceptions.
- Inspect intermediate values to locate incorrect calculations.