Lesson 2 of 3 · Python for AI

Installing Python and Setting Up Your Environment

reading25 min

Part 1: Story

Marcus Chen had been a financial analyst at a mid-size asset management firm in Chicago for eleven years. He could build a discounted cash flow model in Excel while half-asleep. He could pivot a table of ten thousand rows of portfolio data without blinking. But the morning he decided to learn Python for AI -- specifically, to automate the tedious quarterly reporting process that consumed three days of his life every thirteen weeks -- he hit a wall he did not expect.

It was not the code. He had not written any code yet.

It was the installation.

Marcus downloaded Python from a website. He was not sure which version -- 3.9 or 3.12 or something else. The installer asked about PATH and he did not know what that meant, so he skipped it. He opened the command prompt on his Windows laptop and typed python. Nothing happened. He typed python3. "Command not found." He Googled "install Python Windows" and found a dozen conflicting guides, some from 2017. He tried one. Now he had two versions of Python and neither worked the way the tutorial expected.

Then a colleague told him to use Anaconda. He installed that. It was 3 gigabytes. His laptop slowed to a crawl. He opened Anaconda Navigator, stared at a dashboard full of icons he did not recognize -- Spyder, Jupyter, Qt Console, Orange -- and felt the specific kind of despair that comes from realizing you cannot even begin the thing you wanted to begin.

Concept Card

Marcus closed his laptop and did not open it again for two weeks.

When he finally came back to it, he did something different. He deleted everything -- both Python installations, Anaconda, all of it. He followed one clean process from start to finish. Thirty minutes later, he had Python running, a virtual environment set up, and his first script printing output to the terminal. The process he followed is the one you are about to learn.

The difference between Marcus's first attempt and his second was not intelligence or technical ability. It was having a single, clear path instead of a dozen contradictory ones. That is what this lesson gives you.


Part 2: Concept

Why Python Version Matters

Python has two major lineages: Python 2 and Python 3. Python 2 officially died in January 2020. It is gone. Do not use it. Every modern tutorial, every AI library, every tool you will encounter in this course uses Python 3.

But even within Python 3, version matters. As of 2025, the versions you will see are:

  • Python 3.9 -- Old. Still works, but missing useful features.
  • Python 3.10 -- Introduced structural pattern matching (match/case).
  • Python 3.11 -- Significantly faster (10-60% speed improvements). Better error messages.
  • Python 3.12 -- Further performance gains. Improved f-string parsing.
  • Python 3.13 -- Latest stable. Experimental free-threaded mode.
Concept Card

Our recommendation: Install Python 3.11 or 3.12. These are the sweet spot -- modern, fast, widely supported by all AI libraries (PyTorch, TensorFlow, LangChain, the Anthropic SDK, OpenAI SDK). Python 3.13 is fine too, but some niche libraries have not caught up yet.

To check what version you have right now, open your terminal and type:

Bash
python3 --version

If you see Python 3.11.x or Python 3.12.x, you can skip ahead to the virtual environments section. If you see something older, or if the command fails entirely, keep reading.

Installing Python: Step by Step

macOS

Modern Macs (macOS 12.3+) do not come with Python pre-installed. The old system Python 2.7 was removed. You need to install Python 3 yourself.

Option A: Official Installer (Simplest)

  1. Go to python.org/downloads
  2. Download the macOS installer for Python 3.12.x (the big yellow button)
  3. Open the .pkg file and follow the prompts
  4. When installation finishes, open Terminal (search for it in Spotlight with Cmd+Space)
  5. Verify:
Bash
python3 --version

You should see something like Python 3.12.5.

Option B: Homebrew (If You Already Use It)

If you already have Homebrew installed (if you do not know what that is, use Option A):

Tip

Use Installing Python and Setting Up Your Environment in a low-risk branch or scratch project first. That keeps the lesson concrete without making your first attempt carry production pressure.

Bash
brew install python@3.12

Then verify:

Bash
python3 --version
Mac Users: python vs python3

On macOS, the command is python3, not python. Typing just python will either fail or point to an old version. Always use python3 and pip3 on a Mac. You can create an alias later if you want, but for now, train your fingers to type python3.

Windows

Windows does not ship with Python. You must install it yourself. This is the most common place where beginners make mistakes, so follow these steps exactly.

  1. Go to python.org/downloads
  2. Download the Windows installer for Python 3.12.x
  3. Run the installer and -- this is critical -- check the box that says "Add python.exe to PATH" at the bottom of the first screen. This is not checked by default. If you miss this step, Windows will not know where to find Python when you type python in the terminal.
  4. Click "Install Now" (the default settings are fine)
  5. When it finishes, open Command Prompt (search for "cmd" in the Start menu) or PowerShell
  6. Verify:
Bash
python --version

You should see Python 3.12.5 or similar.

The PATH Checkbox Is Not Optional

If you forgot to check "Add python.exe to PATH" during installation, you have two options: (1) Uninstall Python and reinstall it, this time checking the box. (2) Manually add Python to your PATH environment variable. Option 1 is faster and less error-prone. Seriously -- just reinstall. It takes two minutes.

Also verify that pip (Python's package installer) is available:

Bash
pip --version

You should see something like pip 24.0 from C:\Users\YourName\...\pip (python 3.12).

Windows-specific note: On Windows, the commands are python and pip (not python3 and pip3). This is the opposite of macOS. It catches people off guard.

Linux (Ubuntu/Debian)

Most Linux distributions come with Python 3, but it may be an older version. Check first:

Bash
python3 --version

If it is 3.11 or higher, you are good. If it is older, or if the command is not found:

Bash
sudo apt update
sudo apt install python3.12 python3.12-venv python3-pip

Verify:

Bash
python3.12 --version

On Linux, you might need to use python3.12 explicitly if multiple versions coexist.

Tip

If Installing Python and Setting Up Your Environment becomes part of a recurring workflow, document the exact trigger, boundary, and verification step now. Future speed comes from clarity, not from memory.

The Terminal: Your New Best Friend

If you have never used a terminal before, here is the absolute minimum you need to know. The terminal is a text-based interface where you type commands instead of clicking buttons. Think of it as talking directly to your computer.

How to open it:

  • macOS: Cmd+Space, type "Terminal", press Enter
  • Windows: Press Win, type "cmd" or "PowerShell", press Enter
  • Linux: Ctrl+Alt+T (on most distributions)

Essential commands you will use in this course:

Bash
# See where you are (print working directory)
pwd                        # macOS/Linux
cd                         # Windows (just cd alone prints current directory)

# List files in the current folder
ls                         # macOS/Linux
dir                        # Windows

# Change directory
cd Documents               # Move into the Documents folder
cd ..                      # Move up one level
cd ~/projects              # Go to projects folder in home directory (macOS/Linux)
cd %USERPROFILE%\projects  # Windows equivalent

# Create a new folder
mkdir my-python-project    # Works on all platforms

# Clear the screen
clear                      # macOS/Linux
cls                        # Windows

You do not need to memorize all of these right now. You will use them so often in this course that they will become second nature within a week.

Virtual Environments: The Single Most Important Habit

Here is a scenario. You start a project that uses version 1.0 of a library called requests. It works great. Three months later, you start a second project that needs version 2.0 of requests. You install version 2.0. Now your first project breaks because it is incompatible with version 2.0.

This is called a dependency conflict, and it is the number one source of Python headaches for everyone from beginners to senior engineers.

The solution is virtual environments. A virtual environment is a self-contained copy of Python for a specific project. Each project gets its own environment with its own set of installed packages. They do not interfere with each other. Ever.

Run This Workflow in Installing Python and Setting Up Your Environment

  1. Open the integration or environment discussed in this lesson.
  2. Perform one small end-to-end task there instead of in your normal terminal flow.
  3. Write down what got faster, what got slower, and what context you still needed.

Think of it like this: A virtual environment is a separate toolbox for each project. Your carpentry toolbox does not mix with your plumbing toolbox. Same idea.

Creating a Virtual Environment

Navigate to your project folder in the terminal, then run:

Bash
# macOS/Linux
python3 -m venv venv

# Windows
python -m venv venv

This creates a folder called venv inside your project directory. That folder contains a private copy of Python and a place to install packages.

The command breaks down like this:

  • python3 -- Run Python
  • -m venv -- Use the built-in venv module
  • venv -- Name the folder "venv" (this is a convention, not a requirement; you could call it .env or myenv or banana, but venv is what everyone uses)

Activating the Virtual Environment

Creating it is not enough. You have to activate it to use it:

Bash
# macOS/Linux
source venv/bin/activate

# Windows (Command Prompt)
venv\Scripts\activate

# Windows (PowerShell)
venv\Scripts\Activate.ps1

When activated, you will see (venv) at the beginning of your terminal prompt:

Bash
(venv) marcus@laptop:~/my-project$

That (venv) prefix is your confirmation. It means "everything I do now -- every package I install, every script I run -- happens inside this environment."

Deactivating

When you are done working on the project:

Bash
deactivate

The (venv) prefix disappears. You are back to your system Python.

The Golden Rule

Every time you start working on a Python project, activate the virtual environment first. Every time. No exceptions. It takes two seconds and prevents hours of debugging dependency conflicts later. If you see your terminal prompt and there is no (venv) prefix, stop and activate before doing anything else.

pip: Installing Packages

pip is Python's package manager. It downloads and installs libraries from the Python Package Index (PyPI), which hosts over 500,000 packages. With your virtual environment activated, here is how you use it:

Bash
# Install a package
pip install requests

# Install a specific version
pip install requests==2.31.0

# Install multiple packages at once
pip install requests pandas numpy

# See what is installed
pip list

# Uninstall a package
pip uninstall requests

# Save your project's dependencies to a file
pip freeze > requirements.txt

# Install all dependencies from a file (useful when sharing projects)
pip install -r requirements.txt

The requirements.txt file is important. It is a record of exactly which packages (and which versions) your project needs. When you share your code with someone -- or when you set up the project on a new computer -- they can run pip install -r requirements.txt and get the exact same setup you have.

Compare Two Surfaces

  1. Do the same small task in the integration from this lesson and in the plain terminal.
  2. Compare context, edit speed, and review clarity.
  3. Decide which environment deserves to be your default for that task type.

Here is what a requirements.txt file looks like:

requests==2.31.0
pandas==2.2.0
numpy==1.26.3
anthropic==0.18.1
Never Use sudo pip install

On macOS and Linux, you might be tempted to run sudo pip install something when you get a permission error. Do not do this. It installs the package system-wide, which can break your operating system's own Python dependencies. The correct solution is always: use a virtual environment. If you are getting permission errors, you probably forgot to activate your venv.

Setting Up VS Code

VS Code (Visual Studio Code) is the editor we recommend for this course. It is free, fast, and has excellent Python support. You do not need a heavyweight IDE like PyCharm.

Step 1: Install VS Code

Download from code.visualstudio.com and install it.

Step 2: Install the Python Extension

  1. Open VS Code
  2. Click the Extensions icon in the left sidebar (it looks like four squares)
  3. Search for "Python"
  4. Install the one by Microsoft (it will be the top result, with millions of downloads)

This extension gives you:

  • Syntax highlighting -- Python code is color-coded so it is easier to read
  • IntelliSense -- Auto-completion suggestions as you type
  • Linting -- Red underlines when you make a mistake
  • Integrated terminal -- A terminal built right into the editor (Ctrl+` to open it)
  • Debugger -- Step through code line by line (you will use this later)

Step 3: Select Your Python Interpreter

This step connects VS Code to the Python installation in your virtual environment.

Quick Check

What is the main benefit of using Installing Python and Setting Up Your Environment well in Claude Code?

  1. Press Ctrl+Shift+P (Windows/Linux) or Cmd+Shift+P (macOS) to open the Command Palette
  2. Type "Python: Select Interpreter"
  3. Choose the one that points to your virtual environment (it will say something like ./venv/bin/python)

If you do not do this, VS Code might use a different Python installation and you will get confusing errors about missing packages.

Step 4: Test the Integrated Terminal

Press Ctrl+` (backtick) to open the terminal inside VS Code. If your virtual environment was active when you opened VS Code, it should automatically activate in the integrated terminal too. Look for the (venv) prefix.

Bash
(venv) $ python3 --version
Python 3.12.5
(venv) $ pip list
Package    Version
---------- -------
pip        24.0
setuptools 69.5.1

You are now in a professional Python development setup. Same tools, same workflow that working developers use every day.

Common Installation Problems and Fixes

Here are the issues that trip up almost everyone. Bookmark this section -- you will probably come back to it.

Problem: "python is not recognized" or "command not found"

  • Windows: You did not check "Add to PATH" during installation. Reinstall Python with that box checked.
  • macOS: Use python3 instead of python.
  • Linux: Install Python with sudo apt install python3.

Problem: "pip is not recognized"

  • Try pip3 instead of pip (macOS/Linux).
  • On Windows, try python -m pip install package_name instead of pip install package_name.
  • Make sure your virtual environment is activated.

Problem: "Permission denied" when installing packages

  • You are not in a virtual environment. Activate one.
  • Do NOT use sudo. That is the wrong fix.

Problem: Multiple Python versions causing confusion

  • Use python3.12 explicitly instead of python3.
  • Use which python3 (macOS/Linux) or where python (Windows) to see which Python your terminal is using.
  • When in a virtual environment, python inside the venv always points to the right version.

Quick Check

After reading this lesson, what should you validate when applying Installing Python and Setting Up Your Environment?

Problem: VS Code using the wrong Python

  • Open Command Palette (Ctrl+Shift+P / Cmd+Shift+P), type "Python: Select Interpreter", and choose the one in your venv folder.

Problem: PowerShell won't run the activate script on Windows

  • Run this command first: Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
  • This allows PowerShell to run local scripts. It is a one-time fix.

Problem: "No module named 'venv'" on Linux

  • Install it: sudo apt install python3.12-venv

Part 3: Apply

Time to get your hands dirty. Follow these exercises in order. Each one builds on the previous.

Exercise 1: Install Python

If you do not already have Python 3.11+ installed, install it now using the instructions above for your operating system.

Once installed, open your terminal and run:

Bash
python3 --version    # macOS/Linux
python --version     # Windows

Your goal: See a version number of 3.11 or higher printed in your terminal.

If it works, run one more command to confirm pip is available:

Bash
pip3 --version       # macOS/Linux
pip --version        # Windows

You should see pip's version number and the Python version it is associated with. If both commands succeed, you have a working Python installation.

Exercise 2: Create Your Project Folder

Create a dedicated folder for your Python-for-AI work. Do this in the terminal, not by right-clicking in Finder or File Explorer -- start building the muscle memory now.

Bash
# macOS/Linux
cd ~
mkdir python-for-ai
cd python-for-ai

# Windows
cd %USERPROFILE%
mkdir python-for-ai
cd python-for-ai

Verify you are in the right place:

Bash
pwd          # macOS/Linux -- should show /Users/yourname/python-for-ai
cd           # Windows -- should show C:\Users\YourName\python-for-ai

This folder will be your home base for every exercise in this course.

Exercise 3: Create and Activate a Virtual Environment

Inside your python-for-ai folder, create a virtual environment:

Bash
# macOS/Linux
python3 -m venv venv

# Windows
python -m venv venv

Now activate it:

Bash
# macOS/Linux
source venv/bin/activate

# Windows (Command Prompt)
venv\Scripts\activate

# Windows (PowerShell)
venv\Scripts\Activate.ps1

Check: Does your terminal prompt now start with (venv)? If yes, you are in the virtual environment.

Run this to confirm the environment is clean:

Bash
pip list

You should see only pip and setuptools -- nothing else. That is a fresh, clean environment ready for your project's dependencies.

Exercise 4: Install Your First Package

With your virtual environment activated, install the requests library -- a popular Python package for making HTTP requests (talking to web APIs, which you will do constantly when working with AI services):

Bash
pip install requests

Watch the output. You will see pip downloading and installing requests and its dependencies (other packages that requests itself needs).

Now verify it is installed:

Bash
pip list

You should see requests in the list along with its dependencies (charset-normalizer, idnine, urllib3, certifi).

Now test it. Open Python's interactive interpreter:

Bash
python3       # macOS/Linux
python        # Windows

You are now inside the Python REPL (Read-Eval-Print Loop). Type this:

Python
import requests
response = requests.get("https://httpbin.org/json")
print(response.status_code)
print(response.json())

You should see 200 (which means "success") followed by a JSON object. You just made an HTTP request using Python. Type exit() to leave the REPL.

Finally, save your dependencies:

Bash
pip freeze > requirements.txt

Open requirements.txt (you can type cat requirements.txt on macOS/Linux or type requirements.txt on Windows). You will see a list of every installed package and its exact version number. This file is your project's memory -- it records exactly what is installed so anyone (including future-you) can recreate this environment.

Exercise 5: Write and Run Your First Script

Create a file called hello_ai.py. You can do this in VS Code (open the python-for-ai folder with File > Open Folder), or from the terminal:

Bash
# macOS/Linux
touch hello_ai.py

# Windows (PowerShell)
New-Item hello_ai.py

Open the file in your editor and add this code:

Python
import sys
import requests

print("=" * 50)
print("  Python for AI -- Environment Check")
print("=" * 50)
print()
print(f"Python version:  {sys.version}")
print(f"Python location: {sys.executable}")
print()

# Test that requests works
response = requests.get("https://httpbin.org/json")
if response.status_code == 200:
    data = response.json()
    print("HTTP request:    SUCCESS")
    print(f"Response keys:   {list(data.keys())}")
else:
    print(f"HTTP request:    FAILED (status {response.status_code})")

print()
print("Your environment is set up correctly.")
print("You are ready to start learning Python for AI.")

Save the file and run it:

Bash
python3 hello_ai.py      # macOS/Linux
python hello_ai.py       # Windows

You should see a formatted output showing your Python version, confirming the HTTP request succeeded, and telling you your environment is ready. If you see all of that -- congratulations. Your development environment is professional-grade and ready for everything in this course.

If Something Went Wrong

If any exercise above failed, go back to the Common Installation Problems section and check the fix for your specific error message. The three most common issues at this stage are: (1) forgetting to activate the virtual environment before running pip install, (2) using python instead of python3 on macOS, and (3) missing the PATH checkbox on Windows. All three are fixable in under two minutes.


Part 4: Reflect

Remember Marcus from the beginning of this lesson? His first attempt at setting up Python involved two installations, Anaconda, confusion about PATH, and two weeks of avoidance. His second attempt -- the clean one -- took thirty minutes.

You just completed that clean process.

Here is what you now have that most self-taught beginners stumble through for days or weeks:

  • A current version of Python (3.11+) properly installed on your system
  • A project folder with a clean structure
  • A virtual environment that isolates your project's dependencies from everything else
  • pip working correctly inside that environment
  • VS Code configured with the Python extension and pointed at the right interpreter
  • A working script that proves your entire setup is functional
How confident do you feel about applying Installing Python and Setting Up Your Environment in a real project?

This might feel like "just setup" -- not real programming. But professional developers will tell you that environment problems cause more wasted hours than actual bugs. You have eliminated an entire category of future headaches by getting this right from the start.

More importantly, you proved something to yourself: you can work with the command line. You can create files, run commands, install packages, and execute Python scripts. These are the foundational skills that every exercise in this course will build on. None of the AI work we do later -- calling the Claude API, processing data with pandas, building automated workflows -- none of it is possible without this foundation.

Marcus eventually automated his quarterly reporting process. It took him six weeks of learning Python in the evenings, and the script he wrote saved him three days every quarter. But the real turning point was not the day he finished the script. It was the day he got his environment working. That was the day he stopped being someone who wanted to learn Python and became someone who was learning Python.

You are there now. Your environment works. You wrote code and ran it. Everything from here is building on solid ground.

Key Takeaways

  • Understand what Installing Python and Setting Up Your Environment changes about the Claude Code workflow.
  • Connect Installing Python and Setting Up Your Environment back to installing python and setting up your environment so the idea stays tied to a concrete workflow.
  • Apply the lesson in a real project and verify the outcome, not just the setup.
  • Document the pattern if you expect yourself or your team to repeat it.