Setup, venv, and packages
Before you write a line of AI code, you need a reliable workshop: the right Python version, an isolated virtual environment for each project, packages installed and pinned with pip, and secrets kept out of your source code. This lesson sets all of that up step by step and explains what each piece actually does.
What you are setting up
The program that executes Python code. When you run python app.py, the interpreter reads app.py, compiles it to bytecode, and runs it. Different versions (3.11, 3.12, 3.13…) support different language features and packages.
A bundle of reusable Python code published for others to install, such as requests for HTTP or numpy for numeric arrays. Packages are hosted on PyPI, the Python Package Index (pypi.org).
Python's standard package installer. It downloads packages from PyPI and installs them into the currently active Python environment.
A self-contained folder that holds its own Python executable link and its own set of installed packages. Each project gets one, so installing or upgrading a package for project A can never break project B.
Think of the interpreter as the engine, packages as the tools, and the virtual environment as a separate, labelled toolbox per project. AI projects pull in many heavy packages — model SDKs, NumPy, pandas, PyTorch — often with strict version requirements, so isolation is not optional; it is what keeps your projects working next month.
Step 1 — Install Python
You need Python 3.11 or newer. Many AI libraries drop support for old versions quickly, and newer versions are noticeably faster.
macOS
Download the installer from python.org/downloads, or use Homebrew:
brew install [email protected]
Windows
Download the installer from python.org. On the first screen, tick “Add python.exe to PATH” before clicking Install. Windows also installs the py launcher, which lets you pick versions with py -3.12.
Linux (Debian / Ubuntu)
sudo apt update
sudo apt install python3 python3-venv python3-pip
Verify the installation
python3 --version # macOS / Linux
py --version # Windows
Any version from 3.11 upwards is fine; the exact patch number on your machine will differ.
On macOS and Linux, the plain command python may not exist or may point to an old system Python. Use python3 until your virtual environment is active — after activation, python always means the environment's interpreter.
Step 2 — Create a project folder
Every project lives in its own folder. We will use ai-lab throughout this course.
mkdir ai-lab
cd ai-lab
Step 3 — Create a virtual environment
Why not install packages globally?
Imagine an older project that requires numpy<2 and a new project that needs numpy>=2. If both use your machine's global Python, only one version can be installed at a time, and upgrading for one project silently breaks the other. Global installs also need administrator rights on some systems and pollute the Python your operating system depends on. A virtual environment solves all three problems.
python3 -m venv .venv
Read this command piece by piece:
python3— the interpreter that will be copied into the environment.-m venv— “run the module namedvenv”, which ships with Python..venv— the folder to create. The leading dot hides it in most file browsers;.venvis the name editors look for by convention.
Look inside it on macOS or Linux:
ls .venv
bin/ (called Scripts\ on Windows) holds the python and pip commands for this environment, and lib/ is where installed packages will live. You never edit these files by hand.
Step 4 — Activate the environment
Running a small script that puts the environment's bin folder first on your shell's PATH. After that, typing python or pip runs the environment's copies instead of the global ones.
# macOS / Linux (bash, zsh)
source .venv/bin/activate
# Windows PowerShell
.venv\Scripts\Activate.ps1
# Windows Command Prompt
.venv\Scripts\activate.bat
Your prompt now starts with (.venv). Confirm which interpreter is active:
which python # macOS / Linux
where python # Windows
You can also check from inside Python. sys.prefix is the environment Python is running in, and sys.base_prefix is the original installation; they differ only inside a venv.
import sys
print(sys.prefix)
print("inside venv:", sys.prefix != sys.base_prefix)
To leave the environment, run deactivate. Activation only lasts for the current terminal window, so activate again whenever you open a new terminal.
On Windows PowerShell you may see “running scripts is disabled on this system”. Run Set-ExecutionPolicy -Scope CurrentUser RemoteSigned once, then activate again.
Step 5 — Install packages with pip
First upgrade pip itself inside the environment, then install the two packages this course uses early on:
python -m pip install --upgrade pip
python -m pip install requests python-dotenv
Why python -m pip instead of just pip? It guarantees that pip installs into the same interpreter that python refers to. On machines with several Python versions, a bare pip can belong to a different installation — the number one cause of “I installed it but Python says ModuleNotFoundError”.
Useful pip commands:
| Command | What it does |
|---|---|
pip install requests | Install the latest compatible version of a package and its dependencies. |
pip install "requests==2.32.3" | Install an exact version. |
pip install --upgrade requests | Upgrade an installed package. |
pip uninstall requests | Remove a package. |
pip list | Show every package installed in the active environment. |
pip show requests | Show version, location, and dependencies of one package. |
pip freeze | Print installed packages in name==version format, ready for a requirements file. |
Version specifiers
| Specifier | Meaning | Example |
|---|---|---|
== | Exactly this version | pandas==2.2.3 |
>= | This version or newer | requests>=2.31 |
< | Older than this version | numpy<3 |
~= | Compatible release: same major/minor line | openai~=1.40 means ≥1.40 and <2.0 |
Step 6 — Record dependencies in requirements.txt
A plain-text file listing the packages (and usually exact versions) a project needs. Anyone can recreate your environment from it with one command.
python -m pip freeze > requirements.txt
The file looks like this:
certifi==2025.8.3
charset-normalizer==3.4.3
idna==3.10
python-dotenv==1.1.1
requests==2.32.5
urllib3==2.5.0
On a new machine — or for a teammate — recreating the environment is:
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt
pip freeze lists every installed package, including dependencies of dependencies. That is exactly what you want for reproducible deployments. Some teams keep a short hand-written requirements.in with only direct dependencies and generate the pinned file from it with a tool such as pip-tools or uv.
Step 7 — Keep secrets in a .env file
A named value provided to a program by the operating system rather than written in the code — for example OPENAI_API_KEY. Code reads it at runtime, so the secret never appears in your source files or Git history.
Typing export OPENAI_API_KEY=... in every new terminal is tedious, so projects keep local secrets in a .env file and load it with python-dotenv.
OPENAI_API_KEY=sk-your-real-key-here
MODEL_NAME=gpt-4o-mini
import os
from dotenv import load_dotenv
load_dotenv() # reads .env in the current folder into os.environ
api_key = os.getenv("OPENAI_API_KEY")
model = os.getenv("MODEL_NAME", "gpt-4o-mini") # second argument = default
print("model:", model)
print("key loaded:", api_key is not None)
print("key preview:", api_key[:5] + "…")
Now make sure Git never commits the environment folder or your secrets. Create a .gitignore file:
.venv/
.env
__pycache__/
*.pyc
data/
Never print a full API key, paste it in a notebook cell, or commit it. Leaked keys are scraped from public GitHub repositories within minutes. If a key leaks, revoke it in the provider's dashboard immediately — deleting the commit is not enough.
Step 8 — Point your editor at the environment
In Cursor or VS Code, open the ai-lab folder, press Cmd/Ctrl + Shift + P, choose Python: Select Interpreter, and pick the one inside .venv. The editor will then autocomplete installed packages, flag missing imports correctly, and use the right Python when you click Run. New integrated terminals will also activate the environment automatically.
Recommended project layout
ai-lab/
├── .venv/ # virtual environment (never committed)
├── .env # secrets (never committed)
├── .gitignore
├── requirements.txt # pinned dependencies
├── README.md
├── data/ # raw and generated data
├── src/
│ ├── __init__.py
│ └── text_utils.py # reusable helpers
└── scripts/
└── prep.py # entry-point scripts
Alternatives you will hear about
| Tool | What it is | When to use it |
|---|---|---|
venv + pip | Built into Python | Default choice; what this course uses. |
uv | A very fast Rust-based replacement for pip, venv, and pip-tools | Large projects or when install speed matters; commands are similar (uv venv, uv pip install). |
conda / mamba | Environment manager that can also install non-Python libraries (CUDA, MKL) | Data-science and GPU setups that need system-level binaries. |
| Poetry | Dependency manager with lock files and packaging | Libraries you plan to publish to PyPI. |
Troubleshooting common setup errors
| Error | Likely cause | Fix |
|---|---|---|
command not found: python | Only python3 exists, or the venv is not active | Use python3, or activate .venv first. |
ModuleNotFoundError: No module named 'requests' | Package installed into a different interpreter | Activate the venv and run python -m pip install requests. |
externally-managed-environment | Trying to pip install into the system Python (Linux, Homebrew) | Create and activate a virtual environment, then install. |
| Editor shows red import errors but the script runs | Editor is using a different interpreter | Run Python: Select Interpreter and choose .venv. |
No module named venv | Debian/Ubuntu split venv into its own package | sudo apt install python3-venv. |
- Create
ai-lab, make a virtual environment, and activate it. - Install
requestsandpython-dotenv, then saverequirements.txt. - Create a
.envwithMODEL_NAME=demo-modeland print it from Python usingload_dotenv(). - Deactivate, delete
.venv, recreate it, and restore everything withpip install -r requirements.txt.
- Use Python 3.11+ and check it with
python3 --version. - Create one virtual environment per project with
python3 -m venv .venvand activate it in every new terminal. - Install with
python -m pip installso packages land in the right interpreter. - Pin dependencies in
requirements.txtto make installs reproducible. - Keep API keys in environment variables or a git-ignored
.envfile — never in code.