Skip to content

VS Code Setup Guide

From Lightweight Editor to Professional Python IDE


Why Choose VS Code?

Jupyter Notebook vs VS Code

FeatureJupyter NotebookVS Code
Learning CurveEasyMedium
Interactive Analysis⭐⭐⭐⭐⭐⭐⭐⭐⭐
Large Projects⭐⭐⭐⭐⭐⭐⭐
Code Completion⭐⭐⭐⭐⭐⭐⭐
Debugging⭐⭐⭐⭐⭐⭐⭐
Git Integration⭐⭐⭐⭐⭐
Multi-file Management⭐⭐⭐⭐⭐

Recommendations:

  • Data analysis, exploration: Use Jupyter Notebook
  • Writing scripts, large projects: Use VS Code
  • Ideal state: Master both!

Quick Installation and Configuration

Step 1: Download and Install VS Code

Download: code.visualstudio.com

After installation, launch. Interface looks like:

┌────────────────────────────────────┐
│  VS Code                     - □ × │
├────────┬───────────────────────────┤
│        │                           │
│  File  │     Welcome Page          │
│  Tree  │                           │
│        │     Open Folder...        │
│        │     New File...           │
│        │                           │
└────────┴───────────────────────────┘

Step 2: Install Python Extension

  1. Click Extensions icon on left (four squares)
  2. Search for "Python"
  3. Install Microsoft's official Python extension (highest download count)

Essential Extensions List:

Extension NameFunction
Python (Microsoft)Python language support, IntelliSense, debugging
Pylance (Microsoft)Faster code analysis
Jupyter (Microsoft)Run Jupyter Notebooks in VS Code
autoDocstringAuto-generate function documentation

Optional Extensions (Enhance experience):

Extension NameFunction
Python IndentAuto-indent
Better CommentsColorful comments
Error LensInline error display
Material Icon ThemeBeautify file icons
GitHub CopilotAI code completion (subscription required, free for students)

Step 3: Select Python Interpreter

  1. Press Cmd + Shift + P (Mac) or Ctrl + Shift + P (Windows) to open command palette
  2. Type "Python: Select Interpreter"
  3. Choose installed Python version (recommend Anaconda's Python)

Check if configured successfully:

  • Lower left corner should show Python version (e.g., Python 3.11.5)

Writing Python in VS Code

Method 1: Write .py Script Files

Create First Script

  1. New File: FileNew File → Select Python File
  2. Save File: Name it analysis.py
  3. Write Code:
python
# analysis.py
import pandas as pd

# Create data
data = {
    'name': ['Alice', 'Bob', 'Carol'],
    'age': [25, 30, 35],
    'salary': [50000, 60000, 70000]
}

df = pd.DataFrame(data)
print(df)

# Calculate average salary
avg_salary = df['salary'].mean()
print(f"Average Salary: ${avg_salary:,.0f}")
  1. Run Code:
    • Method 1: Click ▶ button in upper right
    • Method 2: Right-click → "Run Python File in Terminal"
    • Method 3: Press Ctrl + Shift + P, type "Run Python File"

Output (displayed in bottom terminal):

    name  age  salary
0  Alice   25   50000
1    Bob   30   60000
2  Carol   35   70000
Average Salary: $60,000

Method 2: Interactive Execution (Like Jupyter)

Use Python Interactive Window

  1. Add # %% in code (create cells):
python
# %% Import libraries and create data
import pandas as pd
import numpy as np

data = {
    'student': ['Alice', 'Bob', 'Carol', 'David'],
    'score': [85, 92, 78, 88]
}
df = pd.DataFrame(data)

# %% Descriptive statistics
print(df.describe())

# %% Visualization
import matplotlib.pyplot as plt
plt.bar(df['student'], df['score'])
plt.ylabel('Score')
plt.title('Student Scores')
plt.show()
  1. Run Cell:

    • Click "Run Cell" that appears above # %%
    • Or press Shift + Enter
  2. View Results: Interactive Window opens on right (similar to Jupyter)

Method 3: Open .ipynb Files Directly in VS Code

  1. Open .ipynb file
  2. VS Code automatically opens in Notebook mode
  3. Experience identical to Jupyter Notebook!

Powerful Features of VS Code

1. Intelligent Code Completion (IntelliSense)

After typing df., VS Code automatically suggests all available methods:

python
df.  # After typing this, suggestions appear
     # - head()
     # - describe()
     # - groupby()
     # - ...

Tips:

  • Press Tab to accept suggestion
  • Press Esc to close suggestions

2. Function Signature Hints

python
pd.read_csv(  # Cursor here shows all parameters
# Hint: filepath_or_buffer, sep=',', header='infer', ...

3. Jump to Definition

python
df = pd.DataFrame(data)
# Hold Cmd (Mac) or Ctrl (Windows), click DataFrame
# Jumps to Pandas source code

4. View Function Documentation

python
df.groupby  # Hover mouse here
# Shows complete function documentation

5. Variable Viewer

In Interactive Window, click "Variables" button to view all variable values (similar to Stata's Variables Manager).

6. Debugger

Set Breakpoint

  1. Click left of line number, red dot appears
  2. Press F5 to start debugging
  3. Code pauses at breakpoint, can inspect variable values

Example:

python
# analysis.py
import pandas as pd

data = {'x': [1, 2, 3], 'y': [4, 5, 6]}
df = pd.DataFrame(data)

# Set breakpoint here
result = df['x'].sum()

print(result)

Debug Shortcuts:

ShortcutFunction
F5Start debugging
F10Step over (skip function)
F11Step into (enter function)
Shift + F5Stop debugging

VS Code Customization

1. Enable Auto Save

FileAuto Save → Check

2. Set Theme

CodePreferencesColor Theme

Recommended themes:

  • Dark+ (default dark theme)
  • Monokai (classic theme)
  • One Dark Pro (popular theme)

3. Set Font

Open settings (Cmd + ,), search "font":

json
{
    "editor.fontFamily": "Fira Code, Menlo, Monaco, 'Courier New', monospace",
    "editor.fontSize": 14,
    "editor.fontLigatures": true  // Ligatures (optional)
}

4. Configure Python Formatter

Open settings, search "python formatting":

json
{
    "python.formatting.provider": "black",
    "editor.formatOnSave": true
}

Install Black:

bash
pip install black

Project Organization: Workspace

Typical Python Project Structure

my_research_project/
├── data/
│   ├── raw/
│   │   └── survey_data.csv
│   └── processed/
│       └── clean_data.csv
├── notebooks/
│   ├── 01_data_cleaning.ipynb
│   └── 02_analysis.ipynb
├── scripts/
│   ├── data_processing.py
│   └── statistical_models.py
├── outputs/
│   ├── figures/
│   └── tables/
├── README.md
└── requirements.txt

Open Project in VS Code:

  1. FileOpen Folder
  2. Select my_research_project folder
  3. Complete file tree displays on left

Essential Shortcuts

General Shortcuts

ShortcutFunction
Cmd + P (Mac) / Ctrl + P (Win)Quick open file
Cmd + Shift + PCommand palette
Cmd + BToggle sidebar
Cmd + JToggle terminal panel
Cmd + \Split screen

Python-Specific Shortcuts

ShortcutFunction
Shift + EnterRun current line/selected code
Ctrl + EnterRun current cell (Interactive mode)
F5Debug run
Ctrl + Shift + 'Open terminal

Code Editing Shortcuts

ShortcutFunction
Cmd + /Comment/uncomment
Alt + ↑/↓Move current line
Shift + Alt + ↑/↓Copy current line
Cmd + DSelect next same word
Cmd + FFind
Cmd + HReplace

Comparison: Stata/R/Python IDEs

IDEStataRPython
Official IDEStata (GUI)RStudioIDLE (not recommended)
Most Popular IDEStataRStudioVS Code / PyCharm
Interactive NotebookR MarkdownJupyter Notebook
Code Completion⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐ (VS Code)
Debugging⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐ (VS Code)

Frequently Asked Questions

Q1: "No module named pandas" when running code?

Solution:

  1. Check Python interpreter in lower left
  2. Ensure selected environment has pandas installed (like Anaconda)
  3. Or run in terminal:
bash
pip install pandas

Q2: VS Code too complex, how should I start?

Recommendation:

  1. Week 1-2: Only use Jupyter Notebook
  2. Week 3-4: Try opening .ipynb files in VS Code
  3. Week 5+: Start writing .py scripts

Q3: How to use virtual environments in VS Code?

Steps:

  1. Create virtual environment:
bash
python -m venv myenv
  1. Activate environment:
bash
# Mac/Linux
source myenv/bin/activate

# Windows
myenv\Scripts\activate
  1. Select this interpreter in VS Code

Hands-on Exercises

Exercise 1: Configure VS Code

  1. Install Python extension
  2. Create a .py file
  3. Write simple data analysis code
  4. Run and view results

Exercise 2: Use Interactive Window

  1. Create a .py file
  2. Use # %% to separate code
  3. Run each cell
  4. View variables window

Exercise 3: Debugging

  1. Write code with errors
  2. Set breakpoints
  3. Use debugger to find errors

AI Programming Assistants: Make Coding Easier

GitHub Copilot (VS Code Extension)

Most mature AI code completion tool, jointly developed by GitHub and OpenAI.

Features:

  • Real-time code suggestions: Type comments or function names, auto-generates complete code
  • Multi-language support: Python, R, Stata (partial), JavaScript, etc.
  • Learns your coding style: Gets smarter with use
  • Free for students and open-source contributors (Apply here)

Example:

python
# Type comment: Calculate the mean income by education level
# Copilot auto-completes:
result = df.groupby('education')['income'].mean()

Pricing: Personal $10/month, free for students


AI Programming IDEs and CLI Tools

Besides VS Code extensions, there are now specialized AI programming tools:

Website: cursor.com

Features:

  • AI-native IDE deeply customized from VS Code
  • Built-in GPT-5, Claude 3.5 models
  • Cmd+K: Select code, describe modification in natural language, AI auto-rewrites
  • Cmd+L: Chat with AI, explain code, debug errors, generate tests
  • Understands entire codebase context (auto-reads whole project)
  • Free tier: 2000 completions/month, Pro $20/month

Use Cases: Writing large projects, rapid prototyping, learning new libraries

2. Google AI Studio (formerly Bard)

Website: aistudio.google.com

Features:

  • Free access to Gemini Pro model
  • Supports code generation, debugging, optimization
  • Can directly export code to Google Colab
  • Downside: Not an IDE, requires copy-paste

3. Claude Code (Anthropic)

Website: claude.ai

Features:

  • Claude 3.5 Sonnet model, strong code understanding
  • Supports long text (200K tokens), can paste entire datasets
  • Ideal for data analysis, statistical modeling code generation
  • Claude Code CLI: Call Claude directly from terminal to generate code
  • Free tier has usage limits, Pro $20/month

4. Aider (Open-Source CLI Tool)

GitHub: github.com/paul-gauthier/aider

Features:

  • AI programming assistant in terminal
  • Supports GPT-4, Claude, Gemini
  • Auto-commits Git records
  • Completely open-source and free (requires own API Key)

Installation:

bash
pip install aider-chat
aider --model gpt-4  # Start AI programming session

AI Programming Tools Comparison

ToolTypePricingBest Use
GitHub CopilotVS Code ExtensionFree for students / $10/moReal-time code completion
CursorStandalone IDEFree / $20/moLarge project development
Claude CodeWeb + CLIFree / $20/moData analysis, learning
Google AI StudioWebCompletely freeCode generation, learning
AiderCLIFree (needs API)Terminal dev, automation

Usage Recommendations

Beginners (first 3 months):

  • Don't over-rely on AI tools
  • Reason: Need to understand basic syntax and logic first
  • Suggestion: Write code by hand first, ask AI when stuck

Intermediate (after 3 months):

  • Use GitHub Copilot to boost efficiency
  • Use Cursor to quickly implement complex features
  • Use Claude to understand and debug complex code

Best Practices:

  1. Don't blindly accept AI-generated code: Always understand every line
  2. Use AI for learning: Have AI explain code, not just generate it
  3. Combined use: Copilot (write code) + Claude (explain code) + traditional debugging

Next Steps

In the next section, we'll introduce Online Python Environments (Google Colab, Kaggle, etc.), allowing you to run Python without local installation.

Keep learning!

Released under the MIT License. Content © Author.