Data Structures and Algorithms
by Albert Major
Types of Errors & How to Fix Them
- Indentation Errors (Python-specific)
- If indentation is inconsistent, Python throws an
IndentationError.
- Fix: Ensure all lines have the correct indentation.
- Syntax Errors (Detected Before Running the Code)
- Python first analyzes the code for structural mistakes before execution.
- Example: Missing colon (
:) at the end of a function or loop declaration.
- Fix: Add the missing syntax (e.g., the colon).
- Runtime Errors (Detected While Running the Code)
- Even if the syntax is correct, errors can occur during execution.
- Example:
TypeError: unsupported operand types for +=: int and str
- This means that Python is trying to add a string (
str) to an integer (int), which is not allowed.
- Fix: Identify where the wrong types are being used and convert them appropriately.
- Debugging a
TypeError Example
- The error occurs when a string is multiplied by an integer, creating unexpected results.
- Investigating the problem:
- Print statements can help but are inefficient.
- Instead, use breakpoints to pause execution and inspect variables step-by-step.
Using Breakpoints for Debugging
- What is a breakpoint?
- A marker in the code that pauses execution at a specific line.
- Allows you to inspect variable values before proceeding.
- Setting up breakpoints in VS Code:
- Click next to a line number to set a red dot (breakpoint).
- Run the program in debug mode instead of normal execution.
- The program stops at the breakpoint, letting you analyze data.
- Debugging Step-by-Step in VS Code:
- Pausing at a breakpoint: Execution stops at the marked line.
- Inspecting variables: Check variable values in the Locals and Globals panels.
- Stepping through code:
- Step Into: Move inside a function call.
- Step Over: Execute a line but stay in the current function.
- Continue: Resume execution until the next breakpoint.
Fixing a New Error: UnboundLocalError
- Error message:
UnboundLocalError: local variable 'result' referenced before assignment
- Why it happens:
- A variable was used before it was assigned a value.
- In Python, when using
+=, Python first reads the variable before modifying it.
- If the variable doesn’t exist yet, it causes an error.
- Fix: Initialize the variable before using
+= to ensure it has a starting value.