AI Tutorial
Home All Courses Blog Interview Prep ↗ 0%
1
Curious builder 0 XP earned · 300 to level 2
0 days Finish a lesson to begin
Badge collection
0 of 5 unlocked
small wins to finish your path
Next lesson →

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.

Last updated: 01 Nov, 2026 · Python 3.11+

What you are setting up

Definition · Python interpreter

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.

Definition · Package

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).

Definition · pip

Python's standard package installer. It downloads packages from PyPI and installs them into the currently active Python environment.

Definition · Virtual environment (venv)

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:

Terminal
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)

Terminal
sudo apt update
sudo apt install python3 python3-venv python3-pip

Verify the installation

Terminal
python3 --version     # macOS / Linux
py --version          # Windows
Python 3.12.4

Any version from 3.11 upwards is fine; the exact patch number on your machine will differ.

Watch out

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.

Terminal
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.

Terminal
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 named venv”, which ships with Python.
  • .venv — the folder to create. The leading dot hides it in most file browsers; .venv is the name editors look for by convention.

Look inside it on macOS or Linux:

Terminal
ls .venv
bin include lib pyvenv.cfg

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

Definition · Activation

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.

Terminal
# 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:

Terminal
which python        # macOS / Linux
where python        # Windows
/Users/you/ai-lab/.venv/bin/python

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.

Python
import sys

print(sys.prefix)
print("inside venv:", sys.prefix != sys.base_prefix)
/Users/you/ai-lab/.venv inside venv: True

To leave the environment, run deactivate. Activation only lasts for the current terminal window, so activate again whenever you open a new terminal.

Watch out

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:

Terminal
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:

CommandWhat it does
pip install requestsInstall the latest compatible version of a package and its dependencies.
pip install "requests==2.32.3"Install an exact version.
pip install --upgrade requestsUpgrade an installed package.
pip uninstall requestsRemove a package.
pip listShow every package installed in the active environment.
pip show requestsShow version, location, and dependencies of one package.
pip freezePrint installed packages in name==version format, ready for a requirements file.

Version specifiers

SpecifierMeaningExample
==Exactly this versionpandas==2.2.3
>=This version or newerrequests>=2.31
<Older than this versionnumpy<3
~=Compatible release: same major/minor lineopenai~=1.40 means ≥1.40 and <2.0

Step 6 — Record dependencies in requirements.txt

Definition · 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.

Terminal
python -m pip freeze > requirements.txt

The file looks like this:

requirements.txt
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:

Terminal
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt
Note

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

Definition · Environment variable

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.

.env
OPENAI_API_KEY=sk-your-real-key-here
MODEL_NAME=gpt-4o-mini
Python
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] + "…")
model: gpt-4o-mini key loaded: True key preview: sk-yo…

Now make sure Git never commits the environment folder or your secrets. Create a .gitignore file:

.gitignore
.venv/
.env
__pycache__/
*.pyc
data/
Watch out

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

Project tree
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

ToolWhat it isWhen to use it
venv + pipBuilt into PythonDefault choice; what this course uses.
uvA very fast Rust-based replacement for pip, venv, and pip-toolsLarge projects or when install speed matters; commands are similar (uv venv, uv pip install).
conda / mambaEnvironment manager that can also install non-Python libraries (CUDA, MKL)Data-science and GPU setups that need system-level binaries.
PoetryDependency manager with lock files and packagingLibraries you plan to publish to PyPI.

Troubleshooting common setup errors

ErrorLikely causeFix
command not found: pythonOnly python3 exists, or the venv is not activeUse python3, or activate .venv first.
ModuleNotFoundError: No module named 'requests'Package installed into a different interpreterActivate the venv and run python -m pip install requests.
externally-managed-environmentTrying 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 runsEditor is using a different interpreterRun Python: Select Interpreter and choose .venv.
No module named venvDebian/Ubuntu split venv into its own packagesudo apt install python3-venv.
Try it
  1. Create ai-lab, make a virtual environment, and activate it.
  2. Install requests and python-dotenv, then save requirements.txt.
  3. Create a .env with MODEL_NAME=demo-model and print it from Python using load_dotenv().
  4. Deactivate, delete .venv, recreate it, and restore everything with pip install -r requirements.txt.
Key takeaways
  • Use Python 3.11+ and check it with python3 --version.
  • Create one virtual environment per project with python3 -m venv .venv and activate it in every new terminal.
  • Install with python -m pip install so packages land in the right interpreter.
  • Pin dependencies in requirements.txt to make installs reproducible.
  • Keep API keys in environment variables or a git-ignored .env file — never in code.