VS Code Setup Guide
From Lightweight Editor to Professional Python IDE
Why Choose VS Code?
Jupyter Notebook vs VS Code
| Feature | Jupyter Notebook | VS Code |
|---|---|---|
| Learning Curve | Easy | Medium |
| 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
- Click Extensions icon on left (four squares)
- Search for "Python"
- Install Microsoft's official Python extension (highest download count)
Essential Extensions List:
| Extension Name | Function |
|---|---|
| Python (Microsoft) | Python language support, IntelliSense, debugging |
| Pylance (Microsoft) | Faster code analysis |
| Jupyter (Microsoft) | Run Jupyter Notebooks in VS Code |
| autoDocstring | Auto-generate function documentation |
Optional Extensions (Enhance experience):
| Extension Name | Function |
|---|---|
| Python Indent | Auto-indent |
| Better Comments | Colorful comments |
| Error Lens | Inline error display |
| Material Icon Theme | Beautify file icons |
| GitHub Copilot | AI code completion (subscription required, free for students) |
Step 3: Select Python Interpreter
- Press
Cmd + Shift + P(Mac) orCtrl + Shift + P(Windows) to open command palette - Type "Python: Select Interpreter"
- 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
- New File:
File→New File→ SelectPython File - Save File: Name it
analysis.py - Write Code:
# 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}")- 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,000Method 2: Interactive Execution (Like Jupyter)
Use Python Interactive Window
- Add
# %%in code (create cells):
# %% 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()Run Cell:
- Click "Run Cell" that appears above
# %% - Or press
Shift + Enter
- Click "Run Cell" that appears above
View Results: Interactive Window opens on right (similar to Jupyter)
Method 3: Open .ipynb Files Directly in VS Code
- Open
.ipynbfile - VS Code automatically opens in Notebook mode
- 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:
df. # After typing this, suggestions appear
# - head()
# - describe()
# - groupby()
# - ...Tips:
- Press
Tabto accept suggestion - Press
Escto close suggestions
2. Function Signature Hints
pd.read_csv( # Cursor here shows all parameters
# Hint: filepath_or_buffer, sep=',', header='infer', ...3. Jump to Definition
df = pd.DataFrame(data)
# Hold Cmd (Mac) or Ctrl (Windows), click DataFrame
# Jumps to Pandas source code4. View Function Documentation
df.groupby # Hover mouse here
# Shows complete function documentation5. Variable Viewer
In Interactive Window, click "Variables" button to view all variable values (similar to Stata's Variables Manager).
6. Debugger
Set Breakpoint
- Click left of line number, red dot appears
- Press
F5to start debugging - Code pauses at breakpoint, can inspect variable values
Example:
# 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:
| Shortcut | Function |
|---|---|
F5 | Start debugging |
F10 | Step over (skip function) |
F11 | Step into (enter function) |
Shift + F5 | Stop debugging |
VS Code Customization
1. Enable Auto Save
File → Auto Save → Check
2. Set Theme
Code → Preferences → Color Theme
Recommended themes:
- Dark+ (default dark theme)
- Monokai (classic theme)
- One Dark Pro (popular theme)
3. Set Font
Open settings (Cmd + ,), search "font":
{
"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":
{
"python.formatting.provider": "black",
"editor.formatOnSave": true
}Install Black:
pip install blackProject 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.txtOpen Project in VS Code:
File→Open Folder- Select
my_research_projectfolder - Complete file tree displays on left
Essential Shortcuts
General Shortcuts
| Shortcut | Function |
|---|---|
Cmd + P (Mac) / Ctrl + P (Win) | Quick open file |
Cmd + Shift + P | Command palette |
Cmd + B | Toggle sidebar |
Cmd + J | Toggle terminal panel |
Cmd + \ | Split screen |
Python-Specific Shortcuts
| Shortcut | Function |
|---|---|
Shift + Enter | Run current line/selected code |
Ctrl + Enter | Run current cell (Interactive mode) |
F5 | Debug run |
Ctrl + Shift + ' | Open terminal |
Code Editing Shortcuts
| Shortcut | Function |
|---|---|
Cmd + / | Comment/uncomment |
Alt + ↑/↓ | Move current line |
Shift + Alt + ↑/↓ | Copy current line |
Cmd + D | Select next same word |
Cmd + F | Find |
Cmd + H | Replace |
Comparison: Stata/R/Python IDEs
| IDE | Stata | R | Python |
|---|---|---|---|
| Official IDE | Stata (GUI) | RStudio | IDLE (not recommended) |
| Most Popular IDE | Stata | RStudio | VS Code / PyCharm |
| Interactive Notebook | ❌ | R Markdown | Jupyter Notebook |
| Code Completion | ⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ (VS Code) |
| Debugging | ⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ (VS Code) |
Frequently Asked Questions
Q1: "No module named pandas" when running code?
Solution:
- Check Python interpreter in lower left
- Ensure selected environment has pandas installed (like Anaconda)
- Or run in terminal:
pip install pandasQ2: VS Code too complex, how should I start?
Recommendation:
- Week 1-2: Only use Jupyter Notebook
- Week 3-4: Try opening .ipynb files in VS Code
- Week 5+: Start writing .py scripts
Q3: How to use virtual environments in VS Code?
Steps:
- Create virtual environment:
python -m venv myenv- Activate environment:
# Mac/Linux
source myenv/bin/activate
# Windows
myenv\Scripts\activate- Select this interpreter in VS Code
Hands-on Exercises
Exercise 1: Configure VS Code
- Install Python extension
- Create a
.pyfile - Write simple data analysis code
- Run and view results
Exercise 2: Use Interactive Window
- Create a
.pyfile - Use
# %%to separate code - Run each cell
- View variables window
Exercise 3: Debugging
- Write code with errors
- Set breakpoints
- 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:
# 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:
1. Cursor (Most Recommended)
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:
pip install aider-chat
aider --model gpt-4 # Start AI programming sessionAI Programming Tools Comparison
| Tool | Type | Pricing | Best Use |
|---|---|---|---|
| GitHub Copilot | VS Code Extension | Free for students / $10/mo | Real-time code completion |
| Cursor | Standalone IDE | Free / $20/mo | Large project development |
| Claude Code | Web + CLI | Free / $20/mo | Data analysis, learning |
| Google AI Studio | Web | Completely free | Code generation, learning |
| Aider | CLI | Free (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:
- Don't blindly accept AI-generated code: Always understand every line
- Use AI for learning: Have AI explain code, not just generate it
- 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!