You found a Python script that promises to write your marketing copy, clean your spreadsheets, or answer customer questions, and the very first instruction is "set up your environment." For most creators, marketers, and founders, that single line is where the project stalls. This guide removes that wall. By the end you will have a working Python installation, a clean and isolated workspace, the core AI packages installed, and a script that prints a real answer from an AI model on your own machine.
You do not need a programming background. You need a computer, about twenty minutes, and the willingness to copy four small blocks of commands into a terminal (the text-based window where you type instructions instead of clicking buttons). This section sits inside the Python AI Fundamentals for Non-Developers track, and it is the foundation every later guide assumes you have finished.
A quick word on the terminal, since it intimidates more newcomers than anything else here. The terminal is just a window that runs one command at a time: you type a line, press Enter, and the computer does exactly what you asked. It does not auto-correct and will not damage anything by being open. The worst that happens when you mistype is an error message you read and fix. Treat every command block below as something you copy, paste with Ctrl+V (or Command+V on Mac), and run — you never have to memorize any of it. If a command seems to hang with no output, that often means it is working, since installs can take a minute or two on a slow connection.
What this guide covers
We work through four numbered steps, each with commands you can paste directly:
- Install the Python runtime so your computer can read and run Python code.
- Create a virtual environment so each project keeps its own private set of packages.
- Install AI packages like the
openaiSDK andhttpxand lock their versions. - Verify the setup by running a short script that talks to a live AI model.
After the steps you get a reference table of the commands and options, a troubleshooting list for the errors beginners hit most, a complete worked example script, and a short list of where to go next.
The problem: why "just install Python" goes wrong
Many computers already ship with some version of Python, and many tutorials tell you to install packages straight into it. That sounds simple and it causes most beginner headaches. The version your operating system bundles is often older than AI libraries require, and it is sometimes used by the system itself, so changing it can break other software.
The deeper trap is shared packages. If you install the openai SDK (the official toolkit for calling OpenAI models) directly into your system Python, then a second project needs a different version, upgrading one quietly breaks the other. You end up with a tangle nobody can untangle. The fix is a virtual environment: a self-contained folder that holds its own copy of Python and its own packages, separate from the system and separate from every other project.
Picture two projects on your laptop. One is a blog-writing script built against openai version 1.30, and one is a data-cleaning script that needs a newer 1.40 release with a small incompatible change. Without isolation, only one version can exist at a time, so installing what one project wants silently breaks the other. With a virtual environment per project, each folder keeps its own pinned versions and they never see each other. The good news for a non-developer is that you get all of that safety from a single command in Step 2, and you never have to think about the mechanics again.
Prerequisites
Before the four steps, make sure you have:
- A computer running macOS, Windows, or Linux with administrator rights to install software.
- Terminal access. On Mac this is the Terminal app; on Windows it is PowerShell or Command Prompt. You open it, type a command, and press Enter.
- An internet connection to download Python and packages.
- About 1 GB of free disk space for Python plus the AI libraries.
- (For the final step only) an AI API key. An API key is a secret password that lets your script call a paid or free-tier model. You can generate one at platform.openai.com/api-keys, or compare free options in Best Free AI APIs for Beginners.
Throughout this guide, commands prefixed with python3 are written for Mac and Linux. On Windows, type python instead of python3 and pip instead of pip3. We will flag the differences as they come up.
Step 1: Install the Python runtime
The runtime is the program that reads your .py files and runs them. Install Python 3.10 or newer because the openai SDK and most current AI libraries no longer support older versions. Python 3.9 reached end-of-life in October 2025, so do not pick it even if a tutorial suggests it.
The cleanest way depends on your operating system, and each has a dedicated guide:
- Mac: Homebrew gives you a modern Python without touching the fragile system copy. Follow How to Install Python for AI Projects on Mac.
- Windows: The official installer works well, as long as you tick one critical box. Follow How to Install Python for AI on Windows.
If you prefer the quick path, download the latest stable release from python.org/downloads and run the installer. On Windows, check the box labeled "Add python.exe to PATH" before clicking Install Now — this single checkbox prevents the most common beginner error.
Once installed, open a fresh terminal window and confirm the version:
# macOS / Linux
python3 --version
pip3 --version
# Windows
python --version
pip --version
You should see something like Python 3.12.4 and a pip version number. pip is the tool that installs Python packages; it ships with Python automatically. If either command returns an error, jump to the troubleshooting section below before continuing.
Two details catch beginners here. First, the version number must start with 3.10 or higher; if you see Python 2.7, an ancient bundled copy answered instead of the one you installed, so use the python3 command rather than python. Second, open a new terminal window after installing Python. The terminal reads its list of available programs once when it starts, so a window opened before the install does not know Python exists yet, and opening a fresh one fixes many "I installed it but the command still fails" reports. On Windows, if the version command works but pip does not, the Add python.exe to PATH checkbox was left unticked during install — re-run the installer, choose Modify, and enable it.
Step 2: Create a virtual environment
Now build the isolated workspace described earlier. Make a project folder, move into it, and create a virtual environment named .venv inside it:
# macOS / Linux
mkdir ai-workspace
cd ai-workspace
python3 -m venv .venv
# Windows
mkdir ai-workspace
cd ai-workspace
python -m venv .venv
The python -m venv .venv command tells Python to build a small private copy of itself in a hidden folder called .venv. Nothing is installed globally; everything will live inside this folder.
Creating the environment is not the same as using it. You must activate it so that python and pip point at the private copy instead of the system one:
# macOS / Linux
source .venv/bin/activate
# Windows (PowerShell)
.venv\Scripts\Activate.ps1
# Windows (Command Prompt)
.venv\Scripts\activate.bat
After activation your prompt shows a (.venv) prefix, your visual proof that you are working inside the isolated environment. Every package you install from now on lands in .venv and nowhere else. When you finish for the day, type deactivate to step back out. For a deeper walkthrough of activation, multiple environments, and common gotchas, see Create a Python Virtual Environment for AI.
Get into the habit of checking for that (.venv) prefix before you run any pip install — it is the most reliable signal that you are installing into the right place. The most common cause of a package "not being there" later is installing it while the environment was inactive, so it landed in system Python instead. Two more habits save time. Name the folder .venv every time rather than inventing a new name per project; the leading dot keeps it out of your file listings, and editors like VS Code auto-detect a folder by that exact name. And because the environment lives entirely inside your project folder, you can delete and rebuild it whenever it gets confused: remove .venv, run python -m venv .venv again, reactivate, and reinstall from requirements.txt. Nothing else on your machine is touched.
Step 3: Install AI packages
With (.venv) showing in your prompt, install the core toolkit. We use the official openai SDK and httpx (a modern HTTP library) rather than the older requests library, because the SDK depends on httpx under the hood and handles authentication, retries, and timeouts for you.
pip install openai httpx python-dotenv
Here is what each package does:
openai— the official SDK for calling OpenAI models with one clean function call.httpx— the HTTP engine the SDK uses to talk to the API; you rarely call it directly but it must be present.python-dotenv— loads secrets such as your API key from a.envfile so they never get hard-coded into your scripts.
Once the install finishes, lock the exact versions into a requirements.txt file. Anyone who later copies your project (including future you, on a new laptop) can recreate the same setup with one command:
pip freeze > requirements.txt
To restore those exact versions elsewhere, you would run pip install -r requirements.txt inside a fresh activated environment. This single file is what makes an AI project reproducible instead of "works on my machine."
Next, store your API key safely. Create a file named .env in your project root containing one line:
OPENAI_API_KEY=sk-your-real-key-here
Immediately tell Git to ignore that file so your secret never gets committed or pushed:
echo ".env" >> .gitignore
Always add .env to .gitignore before your first commit — a leaked API key can be used to run up real charges on your account. If you want to understand how the key authenticates each request, read Understanding LLM APIs.
Two small things make this step go smoothly. The whole filename is literally .env, with no extension, and on Mac and Linux that leading dot hides it from a normal file listing by design. When you write the key, do not wrap it in quotes and do not leave a trailing space; both produce a key that looks correct but fails to authenticate. The value should read OPENAI_API_KEY=sk-... with nothing else on the line. And never paste a real key into a chat window, a screenshot, or a commit — treating it like a password you would never share avoids the most expensive beginner mistake in AI work.
Step 4: Verify the setup
The final step proves every piece works together: Python runs, the environment is active, the SDK is installed, and your key authenticates. Create a file named verify_setup.py in your project root:
import os
from dotenv import load_dotenv
from openai import OpenAI
# Load OPENAI_API_KEY from the .env file into the environment
load_dotenv()
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": "Reply with exactly: Setup verified."},
],
max_tokens=10,
)
print(response.choices[0].message.content)
Run it from your activated environment:
# macOS / Linux
python3 verify_setup.py
# Windows
python verify_setup.py
If you see Setup verified. printed in your terminal, every layer of your stack is working: Python is installed and modern, the virtual environment is active, the openai SDK imported cleanly, your .env file loaded, and your key was accepted by a live model. That one line confirms all five things at once.
It helps to know what each line does, because you will reuse this exact pattern in nearly every AI project. The imports bring in three tools: os reads values from the environment, load_dotenv pulls the contents of .env into that environment, and OpenAI is the client class that talks to the API. Calling load_dotenv() reads your .env file so os.getenv("OPENAI_API_KEY") can find the key. The client object holds your authenticated connection, and client.chat.completions.create(...) is the actual request: you name a model, pass a list of messages, and cap the reply length with max_tokens. The answer comes back nested in the response, which is why you read it from response.choices[0].message.content. If you see an error instead, the troubleshooting section below covers the usual causes, including a missing key or an old model name.
Command and option reference
Keep this table handy while you work. It summarizes the commands and options used above.
| Command / option | What it sets | Default | Effect |
|---|---|---|---|
python -m venv .venv | name of the environment folder | .venv (your choice) | Creates an isolated Python copy inside the named folder. |
source .venv/bin/activate | activation (Mac/Linux) | inactive | Points python and pip at the environment; shows (.venv). |
.venv\Scripts\Activate.ps1 | activation (Windows) | inactive | Same as above, for PowerShell. |
deactivate | leave the environment | — | Returns python and pip to the system version. |
pip install <pkg> | add a package | latest version | Installs into the active environment only. |
pip freeze > requirements.txt | record versions | — | Saves exact installed versions for reproducibility. |
pip install -r requirements.txt | restore versions | — | Recreates the recorded setup in a new environment. |
model="gpt-4o-mini" | which AI model to call | none (required) | Chooses a fast, low-cost model for testing. |
max_tokens=10 | reply length cap | model default | Limits the response so test calls stay cheap. |
Troubleshooting
These are the exact errors beginners hit most, with the cause and a one-line fix for each.
python: command not found(Mac/Linux) or'python' is not recognized(Windows). Your shell cannot find Python on its PATH. On Windows, re-run the installer and tick Add python.exe to PATH; on Mac, install via Homebrew and use thepython3command.pip: command not found. pip is not on your PATH even though Python is. Usepython3 -m pip install <pkg>(orpython -m pipon Windows), which calls pip through Python directly.source: no such file or directory: .venv/bin/activate. The environment was never created, or you are in the wrong folder. Runpython -m venv .venvfirst, and confirm you are insideai-workspacewithpwd(Mac/Linux) orcd(Windows).Activate.ps1 cannot be loaded because running scripts is disabled(Windows PowerShell). PowerShell blocks scripts by default. RunSet-ExecutionPolicy -Scope CurrentUser RemoteSignedonce, then activate again.ModuleNotFoundError: No module named 'openai'. You installed the package outside the active environment, or forgot to activate it. Confirm(.venv)is in your prompt, then re-runpip install openai httpx python-dotenv.openai.AuthenticationError: Incorrect API key provided. Your key is missing, expired, or has stray quotes or spaces in.env. Check the.envline readsOPENAI_API_KEY=sk-...with no quotes; for a full walkthrough see Fix the 401 Unauthorized Error in OpenAI Python.openai.RateLimitErroror a message about quota or insufficient funds. Your key is valid but the account has no available credit, often on a brand-new account before any payment method or free credit is set up. Add a payment method or switch to a free-tier option, then run the script again; nothing is wrong with your Python setup.- The key loads but
os.getenv("OPENAI_API_KEY")returnsNone. Your script is running in a different folder from the.envfile, soload_dotenv()cannot find it. Run the script from the same project folder that holds.env, or pass an explicit path toload_dotenv. Confirming the file is named exactly.env(not.env.txt, which Windows can add silently) clears this up most of the time. NotFoundErroror a message that the model does not exist. Themodelname is misspelled or retired. Use a current small model such asgpt-4o-minifor testing, and copy the name exactly, since model identifiers are case-sensitive and easy to mistype.
Worked example: a setup health-check script
Once your basic verification passes, this slightly larger script gives you a reusable health check. It confirms the Python version, checks that the SDK imported, checks that the key is loaded and shaped correctly, makes a live call, and reports each result in plain language. The script is deliberately defensive: it stops at the first problem it finds and tells you the fix, so you never have to guess which layer failed. Save it as health_check.py and run it any time a project misbehaves.
import os
import sys
from dotenv import load_dotenv
# 1. Confirm the Python version meets the 3.10+ requirement.
# sys.version_info gives the running interpreter's version as numbers,
# so we can compare it directly instead of parsing a string.
major, minor = sys.version_info[:2]
if (major, minor) < (3, 10):
print(f"FAIL: Python {major}.{minor} is too old. Install 3.10 or newer.")
sys.exit(1)
print(f"OK: Python {major}.{minor} detected.")
# 2. Confirm the openai SDK is installed inside THIS environment.
# A failed import here almost always means the virtual environment
# was not active when you ran pip install.
try:
from openai import OpenAI, APIError, AuthenticationError, RateLimitError
except ModuleNotFoundError:
print("FAIL: The openai package is missing. Activate .venv, then run:")
print(" pip install openai httpx python-dotenv")
sys.exit(1)
print("OK: openai SDK imported successfully.")
# 3. Load the .env file and confirm the API key is present and well-formed.
# A key with stray quotes or spaces looks correct but fails to authenticate,
# so we trim whitespace and sanity-check the expected prefix.
load_dotenv()
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
print("FAIL: OPENAI_API_KEY not found. Check your .env file exists here.")
sys.exit(1)
api_key = api_key.strip()
if not api_key.startswith("sk-"):
print("FAIL: The key does not look right. Remove any quotes or spaces in .env.")
sys.exit(1)
print("OK: API key loaded from .env and looks well-formed.")
# 4. Make a tiny live call to confirm the key actually authenticates.
# We keep max_tokens small so this health check stays nearly free to run.
client = OpenAI(api_key=api_key)
try:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Reply with exactly: Setup verified."}],
max_tokens=10,
)
print(f"OK: Model replied -> {response.choices[0].message.content}")
print("All checks passed. Your environment is ready for AI work.")
except AuthenticationError:
print("FAIL: The API key was rejected. Generate a fresh key and update .env.")
sys.exit(1)
except RateLimitError:
print("FAIL: The key works but the account has no available quota or credit.")
sys.exit(1)
except APIError as e:
print(f"FAIL: The API returned an error -> {e}")
sys.exit(1)
Each OK line tells you which layer is healthy, and each FAIL line points to the exact fix. Because the script exits the moment a check fails, the last line you see is always the one that needs your attention. The checks run in dependency order — no point testing your key before confirming the SDK imported — so a clean run reads top to bottom like a checklist. Keeping a script like this in every project turns "something is broken" into a thirty-second diagnosis, and it is just as useful when you rebuild the environment on a new laptop.
Next steps
Your foundation is solid. Build on it in this order:
- Deepen your environment skills. Learn to manage several projects at once in Create a Python Virtual Environment for AI.
- Match your operating system exactly. If anything in Step 1 felt rushed, follow How to Install Python for AI Projects on Mac or How to Install Python for AI on Windows.
- Understand the API you just called. Move on to Understanding LLM APIs to learn what each request actually sends and how billing works.
- Write better instructions for the model. Continue to Prompt Engineering Basics to get reliable, well-formatted output.
Back to Python AI Fundamentals for Non-Developers.