Debugging is the systematic process of locating, analyzing, and fixing errors (bugs) in a program so that it functions as intended. Every programmer encounters bugs — learning to debug efficiently is a core programming skill.
A syntax error occurs when code violates the grammatical rules of Python. The interpreter catches these errors before the program runs.
Common causes:
:) after if, for, while, or defExample:
if x > 5 # SyntaxError: expected ':'
print(x)
A runtime error occurs during program execution, often causing the program to crash. Python raises a specific exception for each type.
Common Python runtime errors:
| Exception | Cause |
|---|---|
ZeroDivisionError | Dividing by zero |
IndexError | Accessing a list index that does not exist |
NameError | Using a variable that has not been defined |
TypeError | Performing an operation on incompatible types |
Example:
x = 10 / 0 # ZeroDivisionError: division by zero
A logical error occurs when the program runs without crashing but produces incorrect results due to a flaw in the programmer's reasoning.
Example:
# Intended to calculate area of rectangle
area = length + width # Bug: should be length * width
When Python raises an exception, it prints a traceback showing:
ZeroDivisionError)Always read the traceback carefully — it points directly to the bug.
Insert print() statements at key points to display variable values and track program flow.
def calculate_area(l, w):
print("l =", l, "w =", w) # Debug print
area = l * w
print("area =", area) # Debug print
return area
Remove or comment out debug prints once the bug is fixed.
Python's IDLE includes a built-in debugger accessible via Debug → Debugger in the menu.
Key debugger features:
| Feature | Description |
|---|---|
| Breakpoint | Pauses execution at a specific line so you can inspect the program state |
| Step | Executes one line at a time |
| Step Over | Executes a function call without stepping into it |
| Watch Variables | Displays current values of variables at each step |
try / except to Handle Runtime ErrorsWrap code that may cause a runtime error in a try/except block to catch and handle the error gracefully.
try:
x = int(input("Enter a number: "))
result = 100 / x
print(result)
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Please enter a valid integer.")
| Error Type | When Detected | Example |
|---|---|---|
| Syntax Error | Before execution | Missing : after if |
| Runtime Error | During execution | ZeroDivisionError |
| Logical Error | After execution (wrong output) | Using + instead of * |