Week 5: Debugging Strategies and Error Messages

CMPSC 100 Computational Expression

Janyl Jumadinova

Debugging in Python

Finding and fixing errors

What is Debugging?

  • 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:

  1. Syntax Errors - Code doesn’t follow Python rules
  2. Runtime Errors - Code runs but crashes during execution
  3. 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 parenthesis
if 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")    # ValueError
result = 10 / 0          # ZeroDivisionError
my_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 numbers
num1 = 10
num2 = 20  
num3 = 30
average = (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 = 0
for num in range(1, 6):
    print(f"num = {num}, total before = {total}")  # Debug
    total = total + num
    print(f"total after = {total}")               # Debug
print(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

Infinite Loops

# Problem:
count = 1
while count <= 5:
    print(count)
    # Forgot to increment count!

# Fix:
count = 1
while count <= 5:
    print(count)
    count = count + 1  # Don't forget this!

Undefined Variables

# Problem:
for i in range(5):
    total = total + i  # total not defined yet!

# Fix:
total = 0              # Initialize first!
for i in range(5):
    total = total + i

Debugging Hardware Code

MicroPython-specific issues:

Import Problems

from machine import Pin  # Make sure this works
import time             # And this too

Hardware Connection

led = Pin("LED", Pin.OUT)
led.on()   # Does the LED actually turn on?

Timing Issues

led.on()
time.sleep(0.1)  # Make sure delays are long enough to see
led.off()

VS Code Debugging Features

Problem Panel

  • View → Problems
  • Shows all syntax errors in your files
  • Updates as you type

Terminal Output

  • Read error messages in the terminal
  • Scroll up to see full error traces

File Comparison

  • Compare your code with working examples
  • Look for small differences

Best Practices

Prevention Tips

  • Write incrementally - add small pieces, test often
  • Use descriptive names - price instead of x
  • Initialize variables before using them

When Debugging

  • Read error messages - they’re helpful, not scary!
  • Make small changes - one at a time
  • Use print statements to see what’s happening
  • Ask for help when stuck - debugging is a skill that takes practice

Remember

  • Every programmer spends time debugging
  • Errors are learning opportunities
  • Getting better at debugging makes you a better programmer!