
(4.3-debugging-vscode)=
# 🧩 4.3 Debugging in VS Code

```{contents}
:depth: 3
```

## 🔰 Tutorial

In this module, you will learn how to debug Python code using VS Code's built-in debugging tools. By the end of this module, you'll be able to:

1. Use print statements to debug code
2. Set breakpoints to pause code execution at specific lines
3. Inspect variables to check their values during execution
4. Step through code line by line
5. Use the debug console for live interaction with your running code
6. Configure custom debug settings in VS Code

### Debugging with Print Statements

The simplest form of debugging is using print statements to display the values of variables at different stages of execution. This method is great for tracking the flow of the program and spotting where things might be going wrong.

#### Steps:
1. Add `print()` statements throughout your code to output the values of key variables.
2. Run your Python file and check the terminal output for these printed messages.

#### Example:
```python
def calculate_area(radius):
    area = 3.14 * radius**2
    print(f"Calculated area: {area}")  # Debugging with a print statement
    return area


radius = 5
print(f"Radius: {radius}")  # Print the value of radius
area = calculate_area(radius)
print(f"Final area: {area}")  # Print the final calculated area
```

**Video Tutorial**: [Debugging Python with Print Statements](https://www.youtube.com/watch?v=GbyXP3_7SBg)

### Setting Breakpoints

Breakpoints allow you to pause the execution of your code at specific lines so that you can inspect the state of the program and variables at that moment. Unlike print statements, breakpoints provide more flexibility and control during debugging.

#### Steps:
1. Open your Python script in VS Code.
2. Click in the margin next to the line number where you want to set a breakpoint. A red dot will appear to indicate the breakpoint.
3. Run the debugger by pressing `F5`, and the code will pause when it hits the breakpoint.

#### Example:
```python
def calculate_area(radius):
    area = 3.14 * radius**2
    return area


radius = 5
area = calculate_area(radius)  # Set a breakpoint on this line
print(f"Area: {area}")
```

**Video Tutorial**: [VS Code Breakpoints Tutorial](https://www.youtube.com/watch?v=cZhMgXgKQdI)

### Inspecting Variables

Once a breakpoint is hit, you can inspect the values of variables at that specific point in time. This helps in understanding the current state of the program and diagnosing any issues.

#### Steps:
1. After the code pauses at a breakpoint, hover over any variable in the editor to see its current value.
2. Alternatively, use the **Variables** section in the Debug Sidebar to see the values of all local and global variables.

#### Example:
```python
def calculate_area(radius):
    area = 3.14 * radius**2
    return area


radius = 10  # Inspect the value of radius here
area = calculate_area(radius)
```

**Video Tutorial**: [Inspecting Variables in VS Code](https://www.youtube.com/watch?v=qw--VYLpxG4)

### Stepping Through Code

Stepping allows you to move through your code line by line, giving you control over the pace of execution. You can "step into" functions, "step over" them, or "step out" of them.

#### Steps:
1. Once the code hits a breakpoint, use the toolbar buttons to:
   - **Step Over** (`F10`): Skip over a function call without entering it.
   - **Step Into** (`F11`): Enter into a function to debug it.
   - **Step Out** (`Shift + F11`): Exit the current function and return to the caller.

#### Example:
```python
def multiply(a, b):
    return a * b


def main():
    x = 5
    y = 10
    result = multiply(x, y)  # Step into this function
    print(f"Result: {result}")


main()
```

**Video Tutorial**: [Stepping Through Code in VS Code](https://www.youtube.com/watch?v=E8dGNupbI4U)

### Using the Debug Console

The debug console allows you to interact with your code while it’s paused. You can execute commands, print variable values, or run functions in real-time.

#### Steps:
1. While the code is paused at a breakpoint, open the **Debug Console** from the bottom panel.
2. In the console, type in variable names to check their values or run Python expressions to see the output.

#### Example:
```python
def divide(a, b):
    return a / b


x = 50
y = 0  # Potential division by zero error
result = divide(
    x, y
)  # Set a breakpoint here and use the debug console to check variable values
```

**Video Tutorial**: [Using the Debug Console in VS Code](https://www.youtube.com/watch?v=-QRyPL5qupU)

### Debug Configurations

You can create custom debug configurations in VS Code to define how your program should be debugged. These configurations are defined in a `launch.json` file.

#### Steps:
1. Open the Command Palette (`Ctrl + Shift + P`) and search for **"Debug: Open launch.json"**.
2. Select the Python environment.
3. Customize the configuration based on your project needs.

#### Example Configuration (`launch.json`):

```json
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "args": ["--verbose"],
            "env": {"DEBUG": "true"},
        }
    ],
}
```

<!-- Pass arguments to the program using the "args" field -->
<!-- Set environment variables using the "env" field -->

**Video Tutorial**: [Setting Up Debug Configurations in VS Code](https://www.youtube.com/watch?v=gLNIRwX3oM4)

### Additional Resources

- [VS Code Debugging Documentation](https://code.visualstudio.com/docs/editor/debugging)
- [Python Debugging in VS Code](https://code.visualstudio.com/docs/python/debugging)
- [Advanced Debugging in VS Code](https://www.youtube.com/watch?v=2oFKNL7vYV8)


## 🚀 Quiz

::::{tab-set}
:sync-group: category

:::{tab-item} W 2024
:sync: w2024

:::

:::{tab-item} Sp/Su 2024
:sync: sp2024

https://q.utoronto.ca/courses/370070/assignments/1393624?display=full_width
:::

:::{tab-item} Sp/Su 2025
:sync: sp2025

https://q.utoronto.ca/courses/393352/assignments/1499725?display=full_width_with_nav
:::

::::

## 📄 Assignment

::::{tab-set}
:sync-group: category

:::{tab-item} W 2024
:sync: w2024

:::

:::{tab-item} Sp/Su 2024
:sync: sp2024

https://q.utoronto.ca/courses/370070/assignments/1394227?display=full_width
:::

:::{tab-item} Sp/Su 2025
:sync: sp2025

https://q.utoronto.ca/courses/393352/assignments/1499726?display=full_width_with_nav
:::

::::
