TAI BUI
Back to curriculum
BuildPython

Where You Write and Run Code

Two windows, one job each: the editor is where code has to work every time, the notebook is where an idea gets to fail cheaply before it earns the right to become code.

TIME: ~50 minutesPREREQUISITES: Phase 0, Lesson 01

Learning Objectives

  • Install VS Code with the extensions and settings that matter for AI work: Python, Pylance, Jupyter, GitLens, Remote SSH, format-on-save, and type checking
  • Launch a notebook (JupyterLab, classic Notebook, or VS Code's Jupyter extension) and use magic commands (`%timeit`, `%%time`, `%matplotlib inline`) to benchmark and visualize inline
  • Apply the "explore in notebooks, ship in scripts" rule, and recognize the common notebook traps: out-of-order execution, hidden state, memory leaks
  • Set up Remote SSH to work on a GPU box as if it were local, and weigh editor alternatives (Cursor, Windsurf, Neovim) for AI work

The Problem

You'll spend thousands of hours doing two different jobs, and they fail in opposite ways if you use the wrong tool. One job is writing code that has to work every time, top to bottom, with no human standing over it. The other is exploring an idea that might not work at all, and finding that out as fast as possible. The editor is built for the first job. The notebook is built for the second. Mix them up and you pay for it daily.

Skip a real editor setup and every session costs you friction: no autocomplete, no type hints, no inline errors, manual formatting, a clunky terminal workflow every time you SSH into a GPU box. The right setup takes 20 minutes. Skipping it costs you 20 minutes every day, forever.

Skip notebooks entirely and you're doing math homework without scratch paper. Every AI paper, tutorial, and Kaggle competition assumes you have one open. Notebooks let you run code in pieces, see outputs inline, and mix code with explanation. But notebooks have real traps of their own, and people use them for everything, including the things they're terrible at: pipelines, reusable utilities, anything that has to run unattended. Get that boundary wrong and you'll spend an afternoon debugging a notebook that "worked five minutes ago."

Know which tool you're in, and why, and both problems disappear.

Warm-up0/3
1. A script is meant to run every night with nobody watching. What has to be true about how it runs?Warm-up
An example crontab entry that runs python retrain.py at 02:00 each night, above five boxes for nights 1 to 5, each marked scheduled run, with a note that nobody is watching.
Example setup: the script name and the 02:00 time are illustrative.
2. What does a code formatter do?Warm-up
A small Python file messy.py with irregular spacing, such as def load( path ) and data=[ 1,2,3 ], feeding into a box labelled formatter whose result is a question mark.
3. Why are machine-learning training jobs often run on a remote machine instead of a laptop?Warm-up
Two cards, your laptop where you write train.py and a remote machine reached over the network, under the question of why a machine-learning training job would run on the remote one.

The Concept

An editor set up for AI work needs five things: language support, type checking, in-editor notebook execution, remote access to wherever the GPU actually lives, and formatting/linting that runs itself so you never think about it.

Mermaid diagram

A notebook is a different shape entirely: not a file you run, but a list of cells, each one either code or markdown, that you can execute in whatever order you click.

Mermaid diagram

Behind every notebook is a kernel: a Python process running in the background. A process, in this sense, is just a running instance of a program, so "a Python process" means an actual running copy of the Python interpreter, sitting there in memory with the value of every variable you've set so far. Run a cell and it ships the code to that kernel, which executes it and sends back the result. Every cell in the notebook shares that one kernel, so variables persist between cells in whatever order you happened to run them, not the order they appear on the page.

Mermaid diagram

That "whatever order you ran them" part is both the entire superpower of a notebook and its favorite way to bite you. Here's what it looks like in practice. Say your notebook has three cells, in this order on the page:

python
# Cell 1
x = 1
python
# Cell 2
print(x)
python
# Cell 3
x = 2

Run them in page order and Cell 2 prints 1, exactly what it looks like it should print. Now click Cell 1, then Cell 2, then Cell 3, then scroll back up and click Cell 2 again. The kernel still has x = 2 from Cell 3, so this second run of Cell 2 prints 2. Nothing on the page changed. Cell 2 still sits above Cell 3, still reads print(x), but now it prints a value that Cell 3, below it, hasn't "happened" yet according to the page. The kernel remembers your click order, not your scroll order, and the notebook gives you no visual signal that the two have diverged.

A script has no equivalent failure mode: it runs top to bottom every time, or it doesn't run. That asymmetry is the real difference between the two tools, and it's the reason you need both, not just a preference for one.

Check: The Concept0/7
1. What is a Jupyter notebook?Define
An open file analysis.ipynb showing a text cell titled Check the data and a code cell that draws 1,000 random numbers with numpy and prints their mean and standard deviation, -0.045 0.987.
2. What is a 'process,' in the sense that a Jupyter kernel is described as a Python process?Define
Terminal where two small Python files demo.py and demo2.py are started in the background and ps lists their two running python3 entries with process IDs and memory sizes, next to the source of each file.
3. What does the Jupyter kernel do?Define
A notebook window containing one cell y = 5 * 2 with an arrow labelled Shift+Enter pointing to a box named kernel, which shows the command python -m ipykernel_launcher -f kernel-3f2a.json and the question what happens in here.
4. What is a cell in a Jupyter notebook?Define
A notebook with four stacked blocks: a text block Load the data, a code block importing pandas, a highlighted code block reading data.csv and showing (1000, 4), and a text block Rows look right, with the highlighted block marked this equals question mark.
5. Why can a script not suffer the out-of-order problem that a notebook has?Explain
A script order_demo.py with three lines x = 1, print(x), x = 2, next to a terminal where python order_demo.py prints 1.
6. In the lesson's Cell 1 / Cell 2 / Cell 3 example (x = 1, print(x), x = 2), why does re-running Cell 2 after Cell 3 print 2 instead of 1?Apply
Three notebook cells in page order, Cell 1 x = 1, Cell 2 print(x), Cell 3 x = 2, beside a click log: Cell 1, Cell 2, Cell 3, then Cell 2 again, with last output 2.
7. Restart the kernel, then run Cell 3 (x = 2), then Cell 1 (x = 1), then Cell 2 (print(x)). What does Cell 2 print?Apply
Three notebook cells in page order, Cell 1 x = 1, Cell 2 print(x), Cell 3 x = 2, beside the session steps: restart the kernel, run Cell 3, run Cell 1, run Cell 2, with Cell 2 prints shown as a question mark.

Build It

Step 1: Install VS Code

VS Code is the recommended editor. Free, runs on every OS, first-class Jupyter notebook support, and an extension ecosystem that covers everything you need for AI work.

Download it from code.visualstudio.com, then verify from the terminal:

bash
code --version

If code isn't found on macOS, open VS Code, press Cmd+Shift+P, type "Shell Command," and select "Install 'code' command in PATH."

Step 2: Install the extensions that matter

Two of the extensions below are worth naming before you install anything. Pylance is a language server, meaning it's what powers autocomplete and jump-to-definition by actually understanding your code's structure (its functions, classes, and types), not just matching text like a search box would. That's the thing people mean when they say LSP, short for Language Server Protocol: the standard that lets an editor talk to a language server like Pylance. Type checking is Pylance using that structural understanding to flag a wrong argument type before you ever run the code. Black and Ruff do a different job: Black formats your code into one consistent style automatically, and Ruff lints it, meaning it scans for likely bugs and style problems and flags them before you run anything. Together they're why "format on save" (Step 3) means you stop thinking about spacing and indentation entirely.

Open the integrated terminal (Ctrl+`` or Cmd+`) and install all eight:

bash
code --install-extension ms-python.python
code --install-extension ms-python.vscode-pylance
code --install-extension ms-toolsai.jupyter
code --install-extension eamodio.gitlens
code --install-extension ms-vscode-remote.remote-ssh
code --install-extension ms-python.debugpy
code --install-extension ms-python.black-formatter
code --install-extension charliermarsh.ruff
ExtensionWhy
PythonLanguage support, virtual env detection, run/debug
PylanceFast type checking, autocomplete, import resolution
JupyterRun notebooks inside VS Code, variable explorer
GitLensSee who changed what, inline git blame
Remote SSHOpen a folder on a remote GPU box as if it were local
DebugpyStep-through debugging for Python
Black FormatterAuto-format on save, consistent style
RuffFast linting, catches common mistakes

code/vscode/extensions.json in this lesson has the full recommendations list. Open the project folder and VS Code will prompt you to install them.

Step 3: Configure settings

Copy code/vscode/settings.json from this lesson, or set these by hand through Settings > Open Settings (JSON):

jsonc
{
    "python.analysis.typeCheckingMode": "basic",
    "editor.formatOnSave": true,
    "editor.rulers": [88, 120],
    "notebook.output.scrolling": true,
    "files.autoSave": "afterDelay"
}

Why each one earns its place:

  • Type checking on basic catches wrong argument types before you run anything: tensor shape mismatches, wrong API parameters, the stuff you'd otherwise find at minute 40 of a training run.
  • Format on save means you never think about formatting again. Black handles it.
  • Rulers at 88 and 120 mark where Black wraps (88) and where docstrings and comments start running too long (120).
  • Notebook output scrolling matters because training loops print thousands of lines. Without it, the output panel explodes.
  • Auto-save exists because you will forget to save, and your training script will quietly run stale code without it.

Step 4: Terminal integration

The integrated terminal is where you run training scripts, monitor GPUs, and manage environments:

jsonc
{
    "terminal.integrated.defaultProfile.osx": "zsh",
    "terminal.integrated.defaultProfile.linux": "bash",
    "terminal.integrated.fontSize": 13,
    "terminal.integrated.scrollback": 10000
}
ActionmacOSLinux/Windows
Toggle terminalCtrl+`Ctrl+`
New terminalCtrl+Shift+`` Ctrl+Shift+``
Split terminalCmd+\Ctrl+\

Split terminals earn their keep here: one running your script, one running nvidia-smi -l 1 or watch -n 1 nvidia-smi.

Step 5: Remote SSH, the most important extension for AI work

You will train on remote machines: cloud VMs, lab servers, Lambda, Vast.ai. Remote SSH opens the remote filesystem, lets you edit files, run terminals, and debug as if it were all local.

  1. Install the Remote SSH extension (done in Step 2).
  2. Ctrl+Shift+P (or Cmd+Shift+P), type "Remote-SSH: Connect to Host."
  3. Enter user@your-gpu-box-ip. VS Code installs its server component on the remote machine automatically.

For passwordless access, you'll generate an SSH key pair first. That's two mathematically linked files: a private key that never leaves your machine, and a public key you hand out to any server you want to log into. The server stores your public key and, when you connect, checks that you hold the matching private key. Prove that and you're in, no password typed, ever.

bash
ssh-keygen -t ed25519 -C "[email protected]"
ssh-copy-id user@your-gpu-box-ip

ssh-keygen generates the key pair on your machine (the private key stays in ~/.ssh/, never share it). ssh-copy-id copies the public half to the remote server's list of trusted keys.

Add the host to ~/.ssh/config:

Host gpu-box
    HostName 203.0.113.50
    User ubuntu
    IdentityFile ~/.ssh/id_ed25519
    ForwardAgent yes

Now Remote-SSH: Connect to Host > gpu-box connects instantly.

Step 6: Pick your notebook interface

Three options, one file format:

InterfaceInstallBest for
JupyterLabpip install jupyterlab then jupyter labFull IDE experience, multiple tabs, file browser, terminal
Jupyter Notebookpip install notebook then jupyter notebookSimple, lightweight, one notebook at a time
VS CodeJupyter extension (already installed in Step 2)Already in your editor, git integration, debugging

All three read and write the same .ipynb file. JupyterLab is the most common in AI work:

bash
pip install jupyterlab
jupyter lab

Step 7: Learn the shortcuts

You operate in two modes: Escape for command mode (blue bar), Enter for edit mode (green bar).

Command mode (most used):

KeyAction
Shift+EnterRun cell, move to next
AInsert cell above
BInsert cell below
DDDelete cell
MConvert to markdown
YConvert to code
ZUndo cell operation
Ctrl+Shift+HShow all shortcuts

Edit mode:

KeyAction
TabAutocomplete
Shift+TabShow function signature
Ctrl+/Toggle comment

Shift+Enter is the one you'll use a thousand times a day. Learn it first.

Step 8: Cell types

Code cells run Python and show the output:

python
import numpy as np
data = np.random.randn(1000)
data.mean(), data.std()

Output: (0.0032, 0.9987)

Markdown cells render formatted text, including headers, bold, italic, tables, and images. They also render LaTeX math, handy for writing out formulas like $E = mc^2$. Use them to document what you're doing and why.

Step 9: Magic commands

These aren't Python. They're Jupyter-specific commands starting with % (line magic) or %% (cell magic).

python
%timeit np.random.randn(10000)

Output: 45.2 us +/- 1.3 us per loop

python
%%time
model.fit(X_train, y_train, epochs=10)

Output: Wall time: 2.34 s

%timeit runs the code many times and averages, so use it for microbenchmarks. %%time runs it once, so use it for training runs.

python
%matplotlib inline

Every plt.plot() or plt.show() now renders directly in the notebook.

python
!pip install scikit-learn

The ! prefix runs any shell command, right from a cell.

python
%env CUDA_VISIBLE_DEVICES

That prints the variable's current value right in the notebook, so you can check which GPU a process can see without opening a separate terminal.

Step 10: Rich display, inline

Notebooks auto-display the last expression in a cell, and they render it properly:

python
import pandas as pd
 
df = pd.DataFrame({
    "model": ["Linear", "Random Forest", "Neural Net"],
    "accuracy": [0.72, 0.89, 0.94],
    "training_time": [0.1, 2.3, 45.6]
})
df

That renders a formatted HTML table, not a text dump. Same with plots:

python
import matplotlib.pyplot as plt
 
plt.figure(figsize=(8, 4))
plt.plot([1, 2, 3, 4], [1, 4, 2, 3])
plt.title("Inline Plot")
plt.show()

The plot appears right below the cell. This is why notebooks dominate AI work. You see the data, the plot, and the code together. For images:

python
from IPython.display import Image, display
display(Image(filename="architecture.png"))

Step 11: Google Colab

Colab is a free Jupyter notebook in the cloud, complete with a GPU, pre-installed libraries, Google Drive integration, and no setup.

  1. Go to colab.research.google.com
  2. Upload any .ipynb file from this course
  3. Runtime > Change runtime type > T4 GPU (free)

Differences from local Jupyter: files don't persist between sessions (save to Drive or download); numpy, pandas, matplotlib, torch, tensorflow, and sklearn come pre-installed; from google.colab import files uploads/downloads files; from google.colab import drive; drive.mount('/content/drive') gives persistent storage; free-tier sessions time out after 90 minutes of inactivity.

Step 12: Alternative editors

Cursor (cursor.com) is a VS Code fork with built-in AI code generation. Same extension ecosystem, same settings format. Everything in Steps 1-5 still applies, so just import the same settings.json and extensions.json.

Windsurf (windsurf.com) is another AI-first VS Code fork. Same story: same extensions, same settings, same Remote SSH support.

Vim/Neovim: if you're already productive here, stay. The minimum setup for AI Python work needs two kinds of plugins: a language server plugin (like nvim-lspconfig) for type checking and autocomplete, and a notebook-execution plugin (like molten-nvim) for running Jupyter cells inside Neovim. Neovim's own documentation and plugin registry stay more current than any fixed list here, so check those for what's actively maintained.

If you don't already use Vim, don't start now. The learning curve competes with learning AI engineering. Use VS Code.

Check: Build It0/29
1. What is a Language Server Protocol (LSP)?Define
A three-line Python file train.py with the cursor on fit, then two JSON messages: the editor sends a textDocument/hover request with line 2 and character 1, and the server replies with contents holding the signature of fit, with a box naming the language server Pylance behind the editor.
Messages simplified for display. Real LSP messages carry more fields, such as a document URI and a request id.
2. What is Pylance?Define
A four-line Python file defining fit(x: list[float], epochs: int) and calling it with the string ten, with a red dashed squiggle under the string and a Problems panel quoting the type error that pyright prints for it.
3. Which VS Code extension enables editing code on a remote GPU machine as if it were local?Define
A laptop with a VS Code window on the left and a GPU box at 203.0.113.50 on the right holding ~/ml-project with train.py, data/ and checkpoints/, joined by a two-way arrow with a dashed pill reading extension question mark.
4. What is an SSH key pair, and why does it let you skip typing a password every time you connect?Define
Terminal where ssh to ubuntu@203.0.113.50 asks for a password, then ssh-keygen -t ed25519 has been run and ls ~/.ssh lists two files, id_ed25519 and id_ed25519.pub, followed by the start of the .pub file.
5. What actually is a `.ipynb` file?Define
A directory listing with analysis.ipynb (509 bytes), clean.py and data.csv beside the same notebook opened in an editor, showing a text cell and a code cell that prints 0.0.
6. What is a magic command in Jupyter?Define
A notebook with five code cells: an ordinary numpy line, then lines starting with %timeit, %%time, %matplotlib inline, and !pip install scikit-learn, with the percent-prefixed lines in orange and no outputs shown.
7. Which magic command makes every `plt.plot()` or `plt.show()` render directly inside the notebook?Define
A notebook code cell that calls plt.plot with the points (1,1), (2,4), (3,2), (4,3) and plt.show(), with a dashed empty frame beneath it marking where the plot should be drawn.
8. What does format on save do?Define
A small Python file utils.py with uneven spacing, such as def add( a,b ), and a Ctrl+S key pill beside the python block of settings.json setting the default formatter to the Black extension and editor.formatOnSave to true.
9. Step 3 sets `editor.rulers` to `[88, 120]` in VS Code settings. What do those two numbers mark?Define
A horizontal scale from column 0 with two dashed vertical rulers at columns 88 and 120, and four blue bars for source lines of 26, 93, 91 and 104 characters labelled code, code, comment and docstring.
10. What happens to a free-tier Google Colab notebook's local files after roughly 90 minutes of inactivity?Define
A free-tier Colab notebook on a T4 GPU whose /content folder holds sample_data, results.csv and model.pt, beside a clock showing that no cell has run for 90 minutes, with a note that Google Drive is not mounted and nothing was downloaded.
11. Why does enabling type checking and format-on-save in VS Code settings matter for AI work?Explain
Terminal from a training script: epochs 1, 2 and 40 print falling loss values, then a traceback ends in a ValueError about a matrix multiply with mismatched sizes.
12. What is the difference between Black and Ruff?Explain
A short Python file scale.py with an unused import os and uneven spacing like def scale(x,k) and y=x*k, above the two commands black scale.py and ruff check scale.py with no output shown.
13. Why does Step 3 turn on `notebook.output.scrolling` in VS Code settings?Explain
A notebook cell running a loop of 5000 training steps that prints a step and loss line each time, showing the first four output lines and a marker for 4,996 more, with the next cell plot_loss_curve() below.
14. Step 3 sets `files.autoSave` to `"afterDelay"`. Why does the lesson say this setting earns its place?Explain
A settings.json line setting files.autoSave to afterDelay, above the four values VS Code accepts for that setting: off, afterDelay, onFocusChange and onWindowChange.
15. Why is Remote SSH called the most important extension for AI work?Explain
A laptop with VS Code and no GPU on the left, connected by arrows marked link question mark to four machines on the right: a cloud VM, a lab server, Lambda and Vast.ai.
16. What is the difference between %timeit and %%time magic commands?Explain
A notebook defining work() that appends to a list calls, then a cell with %timeit work() and a cell with %%time and work(), then print(len(calls)) with its output shown as a question mark.
17. What does running `%env CUDA_VISIBLE_DEVICES` in a cell do, compared to `!pip install scikit-learn`?Explain
A card showing CUDA_VISIBLE_DEVICES=0 in the kernel environment, then two notebook cells, %env CUDA_VISIBLE_DEVICES and !pip install scikit-learn, each with its output shown as a question mark.
18. Why does the lesson recommend against picking up Vim or Neovim if you don't already use it?Explain
Two lists: the first keys a Vim or Neovim beginner must learn (i, Esc, :w, :q, dd, ciw, :%s/a/b/g) beside a study list for AI engineering covering numpy and pandas, PyTorch tensors, training loops, GPUs and Remote SSH, and evaluating models.
19. With the [python] block in settings.json, what happens when you save a Python file?Apply
The python block of settings.json with Black as the default formatter, formatOnSave true and source.organizeImports set to explicit, next to an unsorted train.py (imports sys, os, numpy; def load( p )) with a Ctrl+S key pill.
20. settings.json lists `**/.venv` under search.exclude but not under files.exclude. What does that mean for a .venv folder?Apply
Two lists from settings.json: files.exclude with six patterns (__pycache__, .ipynb_checkpoints, *.pyc, .pytest_cache, .mypy_cache, .ruff_cache) and search.exclude with five (.venv highlighted, node_modules, __pycache__, dist, *.egg-info).
21. A teammate opens a project folder that contains .vscode/extensions.json. What does VS Code do?Apply
A project folder ml-course containing train.py, data/ and a .vscode folder with extensions.json and settings.json, next to the start of extensions.json listing ms-python.python, ms-python.vscode-pylance and ms-toolsai.jupyter of 13 entries, and a note that a teammate opens this folder in VS Code.
22. Which extension appears in extensions.json but not among the eight installed in Step 2?Apply
Two lists side by side: the eight extension IDs installed in Step 2 and the thirteen IDs recommended in extensions.json.
23. In notebook_tips.py, what do the last two prints of dataframe_display report?Apply
Terminal output of the DataFrame part of notebook_tips.py, a table of four models with accuracy, train_time_sec and parameters, followed by the two print lines that pick the best and fastest model by idxmax of accuracy and idxmin of train_time_sec.
24. Run as a plain script, what does inline_plotting in notebook_tips.py do with its figure?Apply
An excerpt of notebook_tips.py showing matplotlib.use("Agg"), plt.subplots, plt.tight_layout, plt.savefig("notebook_plot.png") and the two final prints of inline_plotting, above a terminal where ls shows only notebook_tips.py and python notebook_tips.py is about to run.
25. After you add this block to ~/.ssh/config, which short name do you pick in Remote-SSH: Connect to Host? Host gpu-box HostName 203.0.113.50 User ubuntu IdentityFile ~/.ssh/id_ed25519Apply
The block added to ~/.ssh/config with Host gpu-box, HostName 203.0.113.50, User ubuntu and IdentityFile ~/.ssh/id_ed25519, above the Remote-SSH: Connect to Host command palette prompt Select configured SSH host or enter user@host with its list left as a question mark.
26. You ran ssh-keygen and added the host to ~/.ssh/config, but the GPU box still asks for a password. Which step was likely skipped?Analyze
Terminal after ssh-keygen: ls ~/.ssh shows config, id_ed25519 and id_ed25519.pub, cat ~/.ssh/config shows the gpu-box host entry, and ssh gpu-box still prompts ubuntu@203.0.113.50's password.
27. You edited a training script, started it, and it ran yesterday's version of the code. Which setting would have prevented this?Analyze
An editor tab train.py containing lr = 0.001 and a print of lr, above a terminal where python train.py prints lr = 0.01, the previous value.
28. You have only a laptop with no GPU and want to try a model today for free. What is the sensible setup?Design
Two cards: a laptop with no GPU and a budget of $0, and a goal to try a model today that has to be free.
29. A teammate who is productive in Neovim wants to do AI work in Python. What do you recommend?Design
A Neovim plugins folder listing telescope, treesitter, lualine, gitsigns, which-key and oil, beside a card for the new work, Python for AI, with a note that the plugin list is an example and the teammate is productive in Neovim.
Example setup: the plugin names are illustrative.

Use It

With this setup, your daily workflow looks like:

  1. Open the project folder in VS Code (or connect via Remote SSH to a GPU box).
  2. Write Python with autocomplete, type hints, and inline errors doing the boring work for you.
  3. Run Jupyter notebooks inline with the Jupyter extension, or in JupyterLab if you want a dedicated tab.
  4. Use the integrated terminal for training scripts, uv pip install, and GPU monitoring.
  5. Review changes with GitLens before committing.

Notebooks vs. scripts: when to use which

Use notebooks forUse scripts for
Exploring a datasetTraining pipelines
Prototyping a modelReusable utilities
Visualizing resultsAnything with if __name__
Explaining your workCode that runs on a schedule
Quick experimentsProduction code
Course exercisesPackages and libraries

The rule: explore in notebooks, ship in scripts. A common workflow: explore data in a notebook, prototype the model in the notebook, once it works move the code to .py files, then import those .py files back into the notebook for further experiments.

Common notebook traps

Out-of-order execution. You run cell 5, then cell 2, then cell 7. The notebook works on your machine but breaks the moment someone runs it top to bottom. Fix: Kernel > Restart & Run All before sharing anything.

Hidden state. You delete a cell but the variable it created is still sitting in memory. The notebook looks clean but depends on a ghost cell that no longer exists. Fix: restart the kernel regularly, not just when something breaks.

Memory leaks. Load a 4GB dataset, train a model, load another dataset, and nothing gets freed. Fix: del variable_name and gc.collect(), or just restart the kernel.

Check: Use It0/5
1. What does the rule "explore in notebooks, ship in scripts" mean?Explain
A notebook explore.ipynb with five cells that read data.csv, define clean, build_features and train, and run the whole chain to report accuracy 0.94, beside a project folder holding only data.csv and explore.ipynb.
2. A colleague runs your notebook top to bottom and gets a NameError on a variable, but it worked for you. What is the likely cause and fix?Analyze
A colleague runs the notebook top to bottom: cells 1 to 5 pass, and cell 6, print(len(clean)), stops with NameError: name 'clean' is not defined. A note says the notebook ran fine on the author's machine.
3. You delete a notebook cell that created a variable, but a later cell can still use that variable. What's happening?Analyze
A notebook with a code cell importing numpy, a dashed ghost outline of a deleted cell that held scores = [90, 92, 91], and a later cell sum(scores) / len(scores) that outputs 91.0.
4. You load a 4GB dataset, train a model, then load another dataset in the same notebook session without freeing anything. What trap is this, and what's the fix?Analyze
One notebook cell that loads dataset_a.csv (4 GB) into df_a, trains with model.fit(df_a) and loads dataset_b.csv into df_b, above a memory bar split into df_a 4 GB, model and training, and df_b loading, with a note that nothing was freed.
5. You prototyped a retraining routine in a notebook and now it must run nightly with nobody watching. What should you do?Design
A notebook retrain.ipynb with four cells that load a config, fetch new data, retrain a model and save latest.pt, beside a note that it works when run by hand, above a crontab entry 0 2 * * * with the command left as three question marks.
Example setup: the cell contents and the 02:00 time are illustrative.
Author's Note

The editor/notebook split maps onto a distinction that matters more than the tools themselves: is this code allowed to fail silently, or not? A notebook cell can leave a stale variable in memory and nobody gets hurt, because you're the only one running it, right now, and you'll notice when the numbers look wrong. A script that ships to production doesn't get that grace. It runs unattended, at 3am, on someone else's machine, and "it worked when I ran it out of order" is not a debugging strategy anyone should have to use.

So the actual skill here isn't picking VS Code over Cursor or JupyterLab over Colab — pick whichever, they all read the same files. The skill is noticing, cell by cell, which mode you're actually in. If you're not sure whether what you're writing needs to survive Restart & Run All, that's usually the moment to find out before you've built three more cells on top of it.

Exercises

  1. Install VS Code and every extension from Step 2; confirm Pylance shows type hints and Black formats on save.
  2. Copy code/vscode/settings.json from this lesson into your VS Code config and verify notebook.output.scrolling is on.
  3. Open JupyterLab (or the Jupyter extension in VS Code) and use %timeit to compare list comprehension vs. numpy for building an array of 100,000 random numbers.
  4. Build a notebook with both markdown and code cells that loads a CSV, displays a dataframe, and plots a chart, then run Kernel > Restart & Run All to confirm it survives top-to-bottom execution.
  5. Take code/notebook_tips.py from this lesson, paste it into a Colab notebook, and run it on a free GPU.
  6. If you have access to a remote machine, set up Remote SSH and open a folder on it.

Key Terms

TermWhat people sayWhat it actually means
Kernel"The thing running my code"A separate Python process that executes cells and keeps variables in memory
Cell"A code block"An independently runnable unit in a notebook, either code or markdown
Magic command"Jupyter tricks"Special commands prefixed with % or %% that control the notebook environment
.ipynb"Notebook file"A JSON file containing cells, outputs, and metadata. Stands for IPython Notebook
LSP"Autocomplete engine"Language Server Protocol: a standard for editors to get type info, completions, and diagnostics from a language-specific server
Pylance"The Python plugin"Microsoft's Python language server using Pyright for type checking and IntelliSense
Remote SSH"Working on the server"VS Code extension that runs a lightweight server on a remote machine and streams the UI to your local editor
Format on save"Auto-prettier"The editor runs a formatter (Black, Ruff) every time you save, so code style is always consistent

Further Reading

Code

Ships With