◆ AI All-in-One

Level 2 Agentic Coding · Programming and Tools

Setting Up Your Environment

How to install Python and AI libraries so they keep working. Virtual environments, uv and conda, VS Code, free GPUs on Colab and Kaggle, renting cloud GPUs, and fixing the usual "it worked yesterday" problems.

Level
●●●●● Beginner
Reading
11 min
To learn it well
1 hour to read, an evening to set up
Builds on
1 concept →
↗ Plan a path here

Read first

Python for AI

This leads to

Setting Up a Coding Agent
The full path from zero — 1 concept before this one
  1. Python for AI
  2. Setting Up Your Environment

Read them roughly in this order. See it on the concept map →

Why it matters

Before you can train anything you need somewhere for the code to run. For beginners this is often the most frustrating part of learning AI. It is not hard, but small mistakes produce baffling errors: ModuleNotFoundError for a package you are sure you installed, a library that worked yesterday and breaks today, or a GPU that the code refuses to see.

Almost all of these problems come from one cause: having more than one Python and not knowing which one you are using. This chapter explains how to avoid that with virtual environments, which tools to use, and where to get GPU power when your laptop is not enough. If you only want to try things out, skip the installation entirely and use Google Colab in your browser. Come back here when you want a proper setup on your own machine.

The intuition

Think of a workshop. Python itself is the workbench. Packages such as NumPy and PyTorch are tools. Each project you build needs its own set of tools, sometimes particular versions of them. A two-year-old research repository may need PyTorch 1.13, while your new project needs the latest.

If you throw every tool into one big shared drawer, sooner or later one project's needs break another's. Installing the newest version of a library for project B quietly upgrades it under project A as well, and project A stops working.

A virtual environment gives each project its own drawer. It is simply a folder containing a private copy of Python's package directory. Whatever you install while that environment is active goes into that folder and nowhere else. Delete the folder and the project's packages are gone. Nothing else on your computer is touched.

Your computer System Python used by the operating system don't install into it, never sudo pip install project-a/ train.py, pyproject.toml, uv.lock old-paper-code/ model.py, requirements.txt .venv/ .venv/ python 3.12 torch 2.5 numpy 2.1 pandas 2.2 python 3.10 torch 1.13 numpy 1.24 pandas 1.5 only this project sees these only this project sees these pip install torch with project-a active changes project-a only
Fig. 1 One computer, several isolated environments. Each project folder has its own .venv with its own versions of each package, so upgrading one project cannot break another. The system Python is left alone.

Key idea One project, one virtual environment. Always know which Python you are running. Most "it doesn't work" problems disappear once you follow these two rules.

How it works

The pieces

  • The terminal (also called the command line or shell) is a text window where you type commands. On macOS it is called Terminal. On Windows use PowerShell, or install WSL (the Windows Subsystem for Linux), which gives you a real Linux terminal and avoids many Windows-only problems with AI libraries.
  • The Python interpreter is the program that runs Python code. You may have several on one machine: one that came with the operating system, one you installed, and one inside each virtual environment.
  • A package manager downloads packages and their dependencies (the other packages they need) and installs them. Python's built-in one is pip. Two popular alternatives are uv and conda.
  • An editor or IDE (integrated development environment) is where you write code. VS Code is free and the most common choice. PyCharm and Cursor are popular too.

uv is a fast package and project manager for Python, written in Rust by the company Astral and first released in 2024. It can install Python itself, create virtual environments and install packages, usually many times faster than pip. By 2025 it had become a common default for new projects.

Install it by following the one-line instructions on its website, then:

uv python install 3.12          # download a Python if you don't have one
uv init my-project              # create a project folder with a pyproject.toml
cd my-project
uv add numpy pandas matplotlib scikit-learn torch   # install into ./.venv
uv run python train.py          # run a script inside the project's environment

uv add writes the packages into a file called pyproject.toml, the project's list of requirements, and pins the exact versions in a lockfile, uv.lock. A lockfile records the precise version of every package, including dependencies of dependencies. Someone else, or you in a year's time, can recreate the identical environment with uv sync.

Option 2: plain venv and pip

Python ships with everything needed for virtual environments. This is what most tutorials show, and it is worth understanding even if you use uv:

python3 -m venv .venv                 # create the environment in a folder called .venv
source .venv/bin/activate             # macOS/Linux: switch to it
# .venv\Scripts\activate              # Windows PowerShell equivalent
pip install numpy pandas torch        # installs into .venv only
pip freeze > requirements.txt         # record exact versions
deactivate                            # leave the environment

When an environment is active, your prompt usually shows its name, such as (.venv), and the commands python and pip refer to the copies inside .venv. If you open a new terminal you must activate again. Forgetting to do so is the most common source of ModuleNotFoundError.

Option 3: conda

conda is an older package manager, popular in science, that can install non-Python software too, such as specific versions of compilers or the CUDA libraries. Install the minimal Miniforge distribution rather than the full Anaconda, which is large and has licence conditions for larger organisations.

conda create -n ai python=3.12
conda activate ai
conda install numpy pandas

Conda environments live in a central folder rather than in your project. Mixing conda install and pip install in the same environment works, but can cause conflicts. A common rule is to use conda for Python itself and the heavy compiled pieces, then pip for everything else.

Installing PyTorch and the GPU question

PyTorch is the one package that needs care, because it comes in different builds for different hardware:

  • NVIDIA GPU (Linux or Windows): you need a recent NVIDIA driver. The PyTorch packages bundle their own copy of the CUDA libraries, so you usually do not need to install the CUDA Toolkit separately. Use the install selector on pytorch.org, which prints the right command for your system.
  • Apple silicon Mac (M1 and later): the standard pip install torch includes support for the Mac's built-in GPU through a backend called MPS (Metal Performance Shaders).
  • No GPU: the CPU build works fine for learning, for small models and for everything in the NumPy and Array Thinking, Pandas and Working with Data and scikit-learn chapters.

GPUs and Why AI Needs Them explains what a GPU is and why AI needs one.

VS Code

Install VS Code and its Python extension (published by Microsoft). Open your project folder, then use the command "Python: Select Interpreter" and pick the Python inside your project's .venv. VS Code then runs and debugs your code with the right packages. It also opens Jupyter notebooks directly, so you can use notebooks with your local environment.

Free and cheap GPUs

Your laptop is fine for learning, but training even a modest neural network on images or text is far faster on a GPU. Options, roughly in order of cost:

Your laptop CPU or Apple GPU cost: free good for: learning, NumPy, pandas, scikit-learn, tiny nets limit: speed Colab / Kaggle e.g. NVIDIA T4, 16 GB cost: free tier good for: courses, small CNNs, fine-tuning small models limit: time-outs, quotas Rented cloud GPU e.g. H100 / B200, 80–192 GB cost: dollars per hour good for: real projects, fine-tuning LLMs, long training runs limit: your budget GPU cluster hundreds to thousands cost: up to millions good for: training large models from scratch limit: organisations only start here more power, more cost, more setup
Fig. 2 Where to run your code, from free to expensive. Start on the left and move right only when you hit a real limit. GPU types and limits are as of late 2026 and change often.
  • Google Colab gives you a notebook with a GPU in the browser for free, usually an NVIDIA T4 with 16 GB of memory. Sessions time out after a few idle minutes and a maximum runtime, and free GPU access is not guaranteed at busy times. Paid plans give faster GPUs and longer sessions.
  • Kaggle Notebooks are similar, with a weekly GPU quota (about 30 hours a week as of late 2026, shown in your account settings) and a large library of public datasets.
  • Cloud GPU rental from large providers (AWS, Google Cloud, Azure) or smaller specialist ones gives you a whole machine with one or more data-centre GPUs, charged by the hour. As of late 2026 a single high-end GPU such as an NVIDIA H100 typically costs roughly two to four dollars per hour from specialist providers, and more from the big clouds. Always shut machines down when you finish. You pay for every hour they are on, whether you use them or not.
  • Your own GPU. A desktop NVIDIA card with 12–24 GB of memory is enough to fine-tune small models and to run open language models locally. It is worth it only if you will use it a lot.

Keeping it working

  • Record versions. Use uv.lock or pip freeze > requirements.txt. When you share code, share this file.
  • Rebuild rather than repair. If an environment gets into a tangled state, delete the .venv folder and recreate it from the lockfile or requirements file. It takes a minute and is far quicker than debugging.
  • Leave the system Python alone. macOS and Linux use their built-in Python for their own tools. Never sudo pip install into it.
  • Use version control. Keep your code in git, so you can always return to a version that worked. Do not commit the .venv folder or any file containing passwords or API keys. Put both in .gitignore.
  • Keep secrets out of code. API keys for services such as LLM APIs belong in environment variables, read with os.environ["MY_API_KEY"], not typed into scripts that you might share.

In code

Save this as check_env.py and run it whenever something seems wrong. It tells you exactly which Python is running, whether you are inside a virtual environment, which package versions it can see and whether a GPU is available.

# check_env.py: where am I running, and what do I have?
import sys
import platform
from importlib.metadata import version, PackageNotFoundError

print("Python  ", sys.version.split()[0], "on", platform.system())
print("Running ", sys.executable)          # which python binary is this?
print("In a venv?", sys.prefix != sys.base_prefix)

for pkg in ["numpy", "pandas", "scikit-learn", "matplotlib", "torch"]:
    try:
        print(f"  {pkg:<13}{version(pkg)}")
    except PackageNotFoundError:
        print(f"  {pkg:<13}NOT INSTALLED")

try:
    import torch
    if torch.cuda.is_available():
        print("GPU:", torch.cuda.get_device_name(0))
    elif torch.backends.mps.is_available():
        print("GPU: Apple silicon (MPS)")
    else:
        print("GPU: none, using CPU")
except ImportError:
    pass

On an Apple-silicon Mac, inside a project environment, it printed:

Python   3.14.2 on Darwin
Running  /Users/you/my-project/.venv/bin/python
In a venv? True
  numpy        2.5.5
  pandas       3.1.1
  scikit-learn 1.9.1
  matplotlib   3.11.2
  torch        2.15.0
GPU: Apple silicon (MPS)

Your versions and paths will differ. The line to look at first is Running. If it does not point inside your project's .venv, you are using the wrong Python, and that explains any missing packages. On a Colab GPU machine the last line would name the GPU, for example Tesla T4.

Common pitfalls

  • pip install worked, but import fails. pip installed into a different Python from the one running your code. Use python -m pip install ... (which ties pip to that exact Python) or uv add, and check sys.executable.
  • The notebook does not see your packages. A Jupyter notebook runs on a kernel, which may be a different Python from your terminal's. Select the kernel that belongs to your .venv. See Notebooks: Jupyter and Colab.
  • Python version too new. Big compiled libraries sometimes take a few months to support a new Python release. If installation fails with long compiler errors, try the previous Python version.
  • torch.cuda.is_available() is False on an NVIDIA machine. Usually either the CPU-only build of PyTorch was installed or the NVIDIA driver is too old. Run nvidia-smi in the terminal to check the driver, then reinstall PyTorch using the command from pytorch.org.
  • Forgotten cloud machines. A GPU left running over a weekend can cost hundreds of dollars. Set a billing alert with your provider.

Watch out Never paste an API key, password or cloud credential into a notebook you share, a public GitHub repository or a screenshot. Automated bots scan public repositories for keys within minutes. If you leak one, revoke it immediately in the provider's dashboard.

Where it leads

With a working environment you are ready to:

Later, when projects grow, the same habits scale up. Lockfiles become Docker containers, tracked runs become Experiment Tracking and Reproducibility, and rented GPUs become clusters. Deploying Models covers packaging a model so others can use it.

A bit of history

Python's package story grew in layers. pip became the standard installer around 2008. virtualenv, by Ian Bicking, introduced isolated environments in 2007, and a version of it was built into Python 3.3 as venv in 2012. conda came from Continuum Analytics (now Anaconda Inc.) in 2012, largely to solve the problem of installing scientific packages with compiled C and Fortran code, which pip handled badly at the time. Pip's later support for pre-compiled "wheels" fixed much of that.

Google Colab opened to the public around 2017 and soon added free GPUs, which opened deep learning to anyone with a browser. uv, released by Astral in 2024, replaced several separate tools with one fast program and was quickly adopted. The tools keep changing, but the principle has not: isolate each project and record exactly what it depends on.

Try it

  1. Create a new project with uv (or venv), install NumPy, and run check_env.py. Confirm that Running points inside the project folder.
  2. Open a new terminal without activating the environment and run the script again with plain python3 check_env.py. What changes?
  3. Open Google Colab, switch the runtime type to a GPU, paste in the script and run it. Which GPU did you get?

Hint for 3: in Colab use the "Runtime" menu, then "Change runtime type".

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. You ran pip install pandas successfully, but import pandas in your script fails with ModuleNotFoundError. What is the most likely cause?

  2. Why give each project its own virtual environment?

  3. A colleague wants to recreate exactly the environment your project used a year ago. Which file makes that possible?

  4. On an NVIDIA machine, torch.cuda.is_available() returns False. What are the usual culprits?

  5. You rented a cloud GPU for an experiment that finished on Friday afternoon. What is the most important thing to do?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Docs

uv documentation

Astral · Beginner · Free

Official guide to uv, the fast Python package and project manager: installing Python, projects, lockfiles and scripts.

Tutorial

Getting Started with Python in VS Code

Microsoft · Beginner · Free

Installing VS Code and the Python extension, choosing an interpreter, and running and debugging your first script.

Tool

Google Colab

Google · Beginner · Free

Free Jupyter notebooks in the browser, with GPUs. Nothing to install.

Docs

Kaggle Notebooks documentation

Kaggle · Beginner · Free

How Kaggle's free browser notebooks work, including GPU and TPU quotas and attaching datasets.

Tool

Miniforge

conda-forge · Beginner · Free

A minimal conda installer that uses the community conda-forge channel by default.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/programming/dev-environment.md