Debugging is the process of finding and fixing errors in your code
Named after Admiral Grace Hopper who found an actual bug (moth) in a computer!
Essential skill for every programmer
Most programming time is spent debugging, not writing new code
Types of Errors
Python has three main types of errors:
Syntax Errors - Code doesn’t follow Python rules
Runtime Errors - Code runs but crashes during execution
Logic Errors - Code runs but produces wrong results
Syntax Errors
Errors in the structure of your code
Python can’t understand what you wrote
Program won’t run at all
Common examples:
print("Hello World"# Missing closing parenthesisif num =5: # Should be == not =print("Five") #
Syntax Error Messages
Example error:
print("Hello World"
Error message:
SyntaxError: '(' was never closed
Key parts:
Error type:SyntaxError
Description: What went wrong
Location: Line number where error occurred
Reading Syntax Errors
Example:
if num =5:print("Five")
Error message:
File "main.py", line 1
if num = 5:
^
SyntaxError: invalid syntax
The ^ points to where Python got confused!
Runtime Errors (Exceptions)
Code is syntactically correct but crashes when running
Also called exceptions
Happen when Python can’t complete an operation
Common examples:
number =int("hello") # ValueErrorresult =10/0# ZeroDivisionErrormy_list[10] # IndexError (if list is shorter)
Common Runtime Errors
ValueError
age =int("twenty") # Can't convert "twenty" to integer
ZeroDivisionError
result =10/0# Can't divide by zero
IndexError
word ="HELLO"print(word[10]) # String only has indices 0-4
NameError
print(unknown_variable) # Variable doesn't exist
Error message example:
Traceback (most recent call last):
File "main.py", line 2, in <module>
print(word[10])
IndexError: string index out of range
Logic Errors
Code runs without crashing
But produces wrong results
Hardest to find because no error message!
Example:
# Supposed to calculate average of 3 numbersnum1 =10num2 =20num3 =30average = (num1 + num2 + num3) /2# Should be / 3!print(f"Average: {average}")
Output:Average: 30.0 (Wrong! Should be 20.0)
Debugging Strategies
1. Read Error Messages Carefully
Look at the line number and error type
Read the description - it tells you what’s wrong!
2. Use Print Statements
total =0for num inrange(1, 6):print(f"num = {num}, total before = {total}") # Debug total = total + numprint(f"total after = {total}") # Debugprint(f"Final total: {total}")
3. Test Small Changes
Make one small change at a time
Test immediately after each change
Common Debugging Examples
Indentation Errors
# Problem:if num >5:print("Big number") # Missing indentation!# Fix:if num >5:print("Big number") # Properly indented