Debugging in Python
Debugging is essential in Python programming as it helps
identify, analyze, and fix errors (bugs) in code, ensuring
programs run correctly, efficiently, and reliably. It saves time,
reduces frustration, and improves code quality by catching
issues early before they cause crashes or incorrect outputs.
Types of Bugs (Errors) in Python
Syntax Errors: Violations of Python's grammar rules, like missing colons or unmatched
parentheses. Detected before runtime (e.g., print("Hello") without quotes).
# Missing colon after if statement
if x > 5
print("Greater than 5")
Runtime Errors: Occur during execution, such as division by zero (ZeroDivisionError) or
accessing undefined variables (NameError).
Logical Errors: Code runs without crashing but produces wrong results, like incorrect
calculations in a loop (hardest to spot).
# Intended to add numbers but multiplies instead
a=5
b=3
print("Sum is:", a * b) # Outputs 15 instead of 8
Finding Bugs Using an IDE
IDEs like PyCharm, VS Code, or IDLE streamline debugging through integrated tools.
The process involves:
(1) writing code in the editor.
(2) running it via a debugger (not just "Run").
(3) using syntax highlighting and linting to spot issues instantly.
(4) inspecting variables and call stacks in real-time
(5) stepping through code line-by-line to trace execution flow.
Breakpoints for Pausing Execution
Breakpoints pause program execution at specific lines, allowing inspection of variables, stack traces, and program state
without print statements.
In an IDE:
(1) click the gutter next to a line number to set a breakpoint (red dot appears),
(2) start debugging mode,
(3) execution halts at the breakpoint,
(4) use controls like "Step Over" (next line), "Step Into" (enter functions), or "Resume" to continue. This is ideal for complex
loops or conditionals from prior examples like nested for loops.
numbers = [10, 15, 20, 25, 30] if num % 2 == 0:
total_even = 0 print(num, "is EVEN")
total_odd = 0 total_even += num
for num in numbers:
else:
print("\nProcessing number:",
num) print(num, "is ODD")
total_odd += num
# Breakpoint inside loop print("\nFinal Results:")
breakpoint() print("Sum of even numbers:", total_even)
print("Sum of odd numbers:", total_odd)
How to Run Now try these commands:
In terminal: Check current number
python debug_loop_no_function.py (Pdb) p num
The program will pause at breakpoint() Check totals
for each loop iteration.
(Pdb) p total_even
What You Can Do Inside Debugger
(Pdb) p total_odd
When it stops, you will see something
like: Go to next line
> (Pdb) n
debug_loop_no_function.py(10)<mo
Continue to next breakpoint
dule>()
(Pdb) c
-> if num % 2 == 0:
Quit debugger
(Pdb)
(Pdb) q
What Happens Step-by-Step
For each number in the list:
Loop starts
Breakpoint pauses execution
You inspect variables
if/else decides EVEN or ODD
Totals update
Loop continues