Fundamentals

Choose a Code Editor for Python AI Work

Compare VS Code, PyCharm, JupyterLab and terminal editors for Python AI scripts, then wire your choice to the right virtual environment in one sitting.

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.

Four editor properties with the healthy and unhealthy version of each A three-column matrix. Each row names one property that matters when running Python AI scripts, then shows what a good editor setup looks like and what a broken one looks like. What to check Good sign Bad sign Interpreter shown which Python runs Path ends in .venv visible on screen No interpreter UI you have to guess One-key run no retyped commands Run button or F5 reuses your venv Copy-paste into a shell every time Secrets stay out of your source files Loads keys from .env at run time Key typed into the script itself Output is legible prints and errors Scrollable panel clickable file lines Output vanishes when the run ends
Score any editor against these four rows before you install it; the left column is what to look for, and the right column is the version that will cost you an evening.

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

Three questions that narrow four editors down to one A decision tree. Answering yes to notebook work leads to JupyterLab, yes to remote editing leads to a terminal editor, yes to heavy refactoring leads to PyCharm, and answering no to all three leads to VS Code. Do you work mostly in notebooks? JupyterLab cells, charts, output yes no Editing over SSH or with no desktop? Terminal editor micro, nano or vim yes no Want deep refactor tools, big install? PyCharm full Python-only IDE yes no VS Code the safe default pick
Work down the left-hand questions; the first yes picks your editor, and three noes land you on VS Code, which is what most guides on this site assume.

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.

How the selected interpreter decides whether your import works A flow diagram. Pressing Run hands the file to whichever interpreter the editor has selected; the system Python raises ModuleNotFoundError while the interpreter inside the project virtual environment completes the call. You press Run on first_call.py Editor picks an interpreter path left unset you set it System Python ModuleNotFoundError .venv Python the import succeeds
One setting decides everything downstream: the interpreter your editor picks is the only thing that knows whether the openai package is installed.

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

EditorInterpreter controlBest forWatch out for
VS CodePalette command, shown in status barGeneral AI scripting, most tutorialsNeeds the Python extension installed first
PyCharm CommunityProject setting, add existing environmentLarger multi-file projects, refactoringLarge download, slower first launch
JupyterLabRegistered kernel per environmentData exploration, comparing outputsCells can run out of order and confuse you
Terminal editorWhatever the active shell providesRemote servers, quick fixes over SSHNo 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 .py file 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.

Frequently asked questions

What is the best code editor for a beginner writing Python AI scripts?

VS Code suits most beginners. It is free, it shows the selected Python interpreter in the status bar, it runs a file with one keypress, and it has a built-in terminal. Pick JupyterLab instead if your work is mostly charts and step-by-step data exploration rather than finished scripts.

Why does my script work in the terminal but not in my editor?

Your editor is almost certainly running a different Python than the one you installed packages into. The terminal uses the virtual environment you activated; the editor uses whichever interpreter it selected on its own. Point the editor at the interpreter inside your project's .venv folder and the mismatch disappears.

Do I need PyCharm Professional to work with AI APIs?

No. Calling an AI API is plain Python over HTTPS, so the free PyCharm Community edition handles it fully. The paid edition adds web framework and database tooling you will not touch until you build a hosted app.

Is JupyterLab a code editor or something else?

JupyterLab is a browser-based notebook environment. You write code in cells and run them one at a time, keeping variables alive between runs. It is excellent for exploring data and comparing model outputs, and weaker for scripts you want to schedule or hand to someone else.

How do I keep my API key out of the files I edit?

Put the key in a file called .env, load it at run time with python-dotenv, and list .env in your .gitignore file. Your editor then never displays the key inside a source file, and version control never records it.