By the end of this guide you will have one editor installed, deliberately pointed at the virtual environment your AI packages live in, running a real script with a single keypress, and storing your API key in a file that version control ignores. Budget thirty minutes. Most of that time goes to the download; the part that actually matters — telling the editor which Python to use — takes under a minute once you know where to look.
This guide belongs to Setting Up Python for AI, the section that takes you from a blank machine to a script that talks to a live model. It assumes you already installed Python and made a virtual environment; if not, start with the installer guide for your machine — How to Install Python for AI on Windows, How to Install Python for AI Projects on Mac, or How to Install Python for AI on Linux — and then Create a Python Virtual Environment for AI.
Prerequisites
You need a project folder containing a virtual environment (a private copy of Python and its packages that lives inside that folder, so projects never fight over versions). Create one and install the packages this page uses:
mkdir ai-editor-test
cd ai-editor-test
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install "openai>=1.40" "python-dotenv>=1.0"
Put your API key in a file named .env in that same folder:
OPENAI_API_KEY=sk-your-real-key-here
Then tell version control to ignore it, before you open the folder in any editor:
echo ".env" >> .gitignore
Do this now rather than later. Editors are helpful about committing files, and a key that reaches a public repository is scraped and billed by strangers fast. Nothing else on this page assumes any particular operating system.
The four things that actually matter
Editor reviews argue about themes, plugins and startup speed. None of that decides whether your first AI script runs. Four properties do, and every problem in this guide's troubleshooting section traces back to one of them.
Does it show you which Python it will use? A machine that runs AI code usually has several Pythons on it: the one the operating system ships, the one you installed, and one inside each project's virtual environment. Only the last has your openai package. An editor that displays the interpreter it selected saves you from guessing.
Does it run a file in one keypress? If running your script means switching windows and retyping a command, you will run it less often, and running it often is how you learn what an API actually returns.
Does it keep secrets out of the file? A good setup loads your key from .env at run time. Your key then never appears on screen, never lands in a screenshot, and never gets committed.
Does it show output clearly? You will read a lot of printed text and a lot of tracebacks (the multi-line error report Python prints when something fails). Output that scrolls, persists after the run finishes, and lets you click a file path to jump to the failing line is worth more than any colour scheme.
Step 1 — Install the editor that fits your work
There is no universally best answer, but there is a fast one. Answer three questions about the work you actually do and the choice falls out.
If your days are spent looking at data and charts, and you want to run a few lines, look at the result, then run a few more with the previous results still in memory, install JupyterLab. If you edit files on a machine you reach over SSH (a text connection to a remote computer) or on a server with no desktop, learn one terminal editor — micro is the gentlest, nano is everywhere, vim rewards the investment. If you want a single program that indexes your whole project, renames things safely across files, and ships a strong debugger out of the box, and you do not mind a multi-gigabyte install, choose PyCharm Community. Otherwise choose VS Code, which is where most Python AI tutorials assume you are.
Install whichever one you landed on from its official site or your system package manager. For VS Code, also install the Microsoft Python extension — without it, VS Code treats a .py file as plain text and none of the interpreter features below exist. JupyterLab installs with pip, inside the same virtual environment you already made:
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install "jupyterlab>=4.0" "ipykernel>=6.29"
jupyter lab
Open your project folder in the editor rather than a single file. Every editor here derives its Python settings from the folder it has open, so opening a lone .py file leaves it guessing.
Step 2 — Point the editor at your virtual environment
This is the step people skip, and it is the direct cause of the most common beginner error in AI work: you installed openai successfully, yet the script says the module does not exist. Nothing is broken. Your terminal installed the package into .venv, and your editor ran the file with a completely different Python that has never heard of it.
Here is the setting in each editor, described by what it does rather than where the button sits, since layouts shift between versions.
VS Code. Open the command palette (Ctrl+Shift+P, or Command+Shift+P on Mac), type Python: Select Interpreter, and choose the entry whose path contains your project folder followed by .venv. VS Code then shows that interpreter in the status bar along the bottom, and every new terminal it opens activates the environment for you. To make it permanent for the project, create .vscode/settings.json:
{
"python.defaultInterpreterPath": ".venv/bin/python"
}
PyCharm. In the project settings, find the Python Interpreter entry, choose to add an existing environment rather than a new one, and browse to .venv/bin/python (or .venv\Scripts\python.exe on Windows). PyCharm displays the selected interpreter in the bottom-right corner from then on.
JupyterLab. A notebook does not use a path; it uses a kernel (a named Python process the notebook talks to). Register your environment as a kernel once, with the environment active:
python -m ipykernel install --user --name ai-editor-test --display-name "AI project (.venv)"
Restart JupyterLab and pick that kernel from the kernel selector at the top right of the notebook.
Terminal editor. There is no setting at all. Activate the environment in the shell before you edit or run, and the correct Python is already first on your PATH.
Whatever you chose, verify it instead of trusting it. Save this file as whoami.py and run it from inside the editor, not from your terminal:
import sys
print("Interpreter:", sys.executable)
print("Version:", sys.version.split()[0])
try:
import openai
print("openai version:", openai.__version__)
except ModuleNotFoundError:
print("openai is NOT installed for this interpreter")
The printed interpreter path must contain .venv. If it does not, the setting did not take effect, and no amount of reinstalling packages will fix it.
Step 3 — Run a real AI script in one keypress
Now wire the whole loop together. Create first_call.py in the project folder:
import os
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv() # reads .env from the project folder; .env is in .gitignore
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You answer in one short sentence."},
{"role": "user", "content": "What does a code editor do that a text editor does not?"},
],
)
print(response.choices[0].message.content)
print("Tokens used:", response.usage.total_tokens)
Run it without leaving the editor. In VS Code, press the run control on the open file or use the Run and Debug panel; in PyCharm, use the run action on the current file; in JupyterLab, paste the code into a cell and press Shift+Enter; in a terminal editor, save and run python first_call.py in the shell where the environment is active.
You should see one sentence of model output followed by a token count. If you see a traceback instead, read the last line first — it names the error type — and check it against the next section. Reading tracebacks quickly is its own skill, covered in Read a Python Traceback in Five Minutes.
Notice what the script does not contain: your key. load_dotenv() reads .env into the process environment at start-up, and os.environ["OPENAI_API_KEY"] pulls it from there. Using square brackets rather than os.getenv is deliberate — a missing key fails immediately with a clear KeyError instead of sending an empty string to the API and returning a confusing authentication error.
Step 4 — Lock down .gitignore and .env before you share anything
Editors make committing code a two-click action, which is exactly why the ignore list has to be right before you use it. Create .gitignore in the project folder with this content:
.venv/
.env
__pycache__/
*.pyc
.ipynb_checkpoints/
.vscode/
.idea/
The first two lines protect you: .venv/ keeps hundreds of megabytes of installed packages out of the repository, and .env keeps your key private. The last two lines keep each person's editor preferences out of everyone else's checkout. If you deliberately want to share .vscode/settings.json so teammates get the same interpreter path, remove that line and commit just that file.
Confirm the protection actually works before your first commit:
git init
git add .
git status --short
If .env appears in that list, the ignore rule is not being applied — usually because .gitignore sits in a different folder from .env, or because the file was already tracked from an earlier commit. Untrack it with git rm --cached .env and commit again.
Keep a second file called .env.example that lists the variable names with no values, and commit that one. It tells anyone cloning your project exactly which keys they need to supply. When you move from your laptop to a server or scheduler, the .env file stops being the right answer; Manage API Keys Safely in Production covers what replaces it.
Quick reference: the four options compared
| Editor | Interpreter control | Best for | Watch out for |
|---|---|---|---|
| VS Code | Palette command, shown in status bar | General AI scripting, most tutorials | Needs the Python extension installed first |
| PyCharm Community | Project setting, add existing environment | Larger multi-file projects, refactoring | Large download, slower first launch |
| JupyterLab | Registered kernel per environment | Data exploration, comparing outputs | Cells can run out of order and confuse you |
| Terminal editor | Whatever the active shell provides | Remote servers, quick fixes over SSH | No interpreter warnings, no click-to-error |
You are not marrying any of these. Both VS Code and PyCharm open notebook files, and JupyterLab happily edits plain .py files, so switching later costs an hour, not a rewrite.
Troubleshooting
ModuleNotFoundError: No module named 'openai' — the editor ran a Python that does not have your packages. Run the whoami.py script from Step 2 inside the editor and confirm the path contains .venv; if it does not, reselect the interpreter. The full diagnosis lives in Fix ModuleNotFoundError: No Module Named openai.
KeyError: 'OPENAI_API_KEY' — load_dotenv() did not find your .env. It searches upward from the current working directory, and editors sometimes run scripts from the repository root instead of the file's folder. Either move .env beside the file you run, or pass an explicit path: load_dotenv("/full/path/to/.env").
openai.AuthenticationError: Error code: 401 — the key loaded but the API rejected it. Common causes are a trailing space in .env, quotes wrapped around the value, or a revoked key. Never put quotes around values in a .env file. See Fix the 401 Unauthorized Error in OpenAI Python.
A JupyterLab cell reports a missing module the terminal can import — the notebook is attached to the wrong kernel. Re-run the ipykernel install command from Step 2 with the environment active, restart JupyterLab, and reselect the kernel in the open notebook.
When to use this vs. alternatives
- A full editor vs. a notebook. Use a notebook while you are still deciding what the code should do, because keeping data in memory between runs saves you re-fetching it. Move to a plain
.pyfile the moment you want to schedule the work or hand it to someone else — schedulers such as those in Schedule Python AI Jobs with GitHub Actions run files, not notebooks. - A local editor vs. a hosted browser notebook. A hosted notebook needs no install and is fine for a one-off experiment, but your key lives on someone else's machine and your files vanish when the session ends. Anything you will run more than twice belongs on your own disk.
- VS Code vs. PyCharm. Choose VS Code if you also touch web files, YAML or Markdown, since it handles everything in one window. Choose PyCharm if your project has grown past a handful of Python files and you want rename-across-project and a debugger that needs no configuration.
Whichever way you went, the win is the same: an editor that names the Python it will use, runs your file with a keypress, and never shows your API key on screen. That setup removes the single largest source of confusion in early AI work, so the next problem you hit will be an interesting one about models rather than a boring one about paths. When you are ready to start calling models in earnest, OpenAI vs Anthropic API for Beginners is a good next stop. Back to Setting Up Python for AI.
Related guides
- Create a Python Virtual Environment for AI — build the environment your editor needs to point at.
- Fix ModuleNotFoundError: No Module Named openai — the deep fix for the interpreter mismatch this page prevents.
- How to Install Python for AI on Linux — get a working Python on a Linux machine or server first.
- Debugging Python AI Errors — the main guide for reading and fixing the errors your editor surfaces.
- Count Tokens in Python Before You Send — once scripts run easily, watch what each run costs.