Lesson 1 of 3 · Python for AI

Why Python for AI?

reading20 min

Three years ago, Priya Chandran was a corporate immigration attorney at a mid-size firm in Chicago. She spent her days reviewing visa petitions -- H-1B applications, L-1 transfers, employment-based green cards. The work was important, but the process was crushing. Every petition required cross-referencing government databases, extracting data from employer letters, checking eligibility against shifting USCIS policy memos, and drafting narratives that hit specific legal standards. Each case could take six to ten hours of research and drafting.

One evening, while reading a legal tech newsletter, she stumbled across a blog post about using Python to call the OpenAI API. The author -- a patent attorney -- had written a 40-line script that took an inventor's technical description, cross-referenced it against a database of prior art summaries, and generated a first draft of patent claims. Priya didn't understand a single line of the code. But she understood the outcome: work that took an afternoon was happening in seconds.

She spent the next six weekends learning Python. Not from a computer science textbook. Not from a 40-hour bootcamp. She learned just enough to read files, call APIs, and glue outputs together. Her first real script was embarrassingly simple -- it read a scanned employer support letter (via an OCR API), extracted the job title, salary, and duties, then compared them against Department of Labor wage data she'd downloaded as a CSV. If something looked off, the script flagged it.

Concept Card

That script saved her two hours per case. She was handling 15 cases a week. That's 30 hours -- almost an entire second attorney -- recovered through a script she wrote in a single Saturday.

Within a year, Priya had built a suite of Python tools: an intake form processor that auto-populated petition templates, a compliance checker that flagged missing documents before filing, and a drafting assistant that generated first-pass support letters using Claude's API. Her firm promoted her. Two other attorneys asked her to teach them. She started an internal workshop called "Python for Lawyers."

Priya isn't a developer. She can't build a web application from scratch. She doesn't know what a binary tree is, and she doesn't care. But she can write Python well enough to make AI work for her -- and that skill changed her career.

This lesson is about why Python is the tool that makes that possible, and why you can learn it too -- regardless of your background.


The Language That Won AI

Let's get the obvious question out of the way: why Python? There are hundreds of programming languages. Why did this particular one become the language of artificial intelligence?

Concept Card

The answer isn't a single reason. It's a confluence of factors that built on each other over two decades, creating a self-reinforcing ecosystem that's now almost impossible to displace.

#1

Most-Used Programming Language

Python has held the top position in the TIOBE Index since 2021 and is the #1 language for data science and machine learning according to the 2025 Stack Overflow Developer Survey.

Readability Is Not a Minor Feature

Most programming languages were designed by computer scientists for computer scientists. Python was designed by Guido van Rossum in 1991 with a radical idea: code should be readable by humans first, machines second.

Compare how you'd filter a list of numbers in three different languages:

JavaScript:

javascript
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens);

Java:

java
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> evens = numbers.stream()
    .filter(n -> n % 2 == 0)
    .collect(Collectors.toList());
System.out.println(evens);

Python:

Python
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = [n for n in numbers if n % 2 == 0]
print(evens)

The Python version reads almost like English: "give me every n from numbers if n is even." No type declarations. No semicolons. No curly braces. No .stream().filter().collect() ceremony.

This matters enormously for AI work. When you're writing a script to process data and send it to an API, you don't want to fight with the language. You want to think about the problem -- the prompt engineering, the data pipeline, the output format -- not the syntax.

The Ecosystem Effect

Readability got Python its first users. But what locked in Python's dominance was the ecosystem -- the massive library of tools built on top of it. Here's a timeline of how this happened:

2006 -- NumPy 1.0 launches, giving Python fast numerical computing. Scientists who were using MATLAB and Fortran start switching.

2008 -- pandas appears, making data manipulation in Python as easy as working with a spreadsheet. Data analysts start switching from R and Excel.

Warning

Do not let Why Python for AI become a hidden assumption. If teammates cannot see the rule, config, or verification path, Claude will behave inconsistently across sessions.

2010 -- scikit-learn brings machine learning to Python with a clean, consistent API. model.fit(), model.predict() -- three lines of code to train a classifier.

2015 -- TensorFlow (Google) and Keras bring deep learning to Python. Researchers who were using C++ and Lua switch overnight.

2016 -- PyTorch (Facebook) gives researchers an even more Pythonic deep learning framework. Academic AI research becomes almost exclusively Python.

2020 -- Hugging Face Transformers makes state-of-the-art NLP models accessible with three lines of Python code.

2022–2024 -- OpenAI, Anthropic, Google all release Python SDKs as their primary API interfaces. The large language model revolution runs on Python.

Each wave brought a new community into Python -- scientists, data analysts, ML engineers, AI researchers, and now professionals like you. Each community built tools that attracted the next community. This flywheel has been spinning for nearly 20 years, and it shows no signs of slowing down.

Python by the Numbers

According to the 2025 Stack Overflow Developer Survey, Python is the most commonly used programming language overall, and the #1 language for data science and machine learning by a wide margin. GitHub's Octoverse report shows Python repositories related to AI grew by over 150% between 2023 and 2025. The TIOBE Index has ranked Python #1 since 2021. Every major AI company -- OpenAI, Anthropic, Google DeepMind, Meta AI, Stability AI -- uses Python as its primary SDK language.

Why Not JavaScript? Or R? Or Something Else?

Fair question. Let's address the alternatives directly.

JavaScript is the language of the web. It runs in every browser. If you're building a web interface, you'll eventually use some JavaScript. But JavaScript was never designed for data work. It doesn't have a pandas equivalent. Its numerical computing is slower. And while every AI company offers a JavaScript SDK, those SDKs are always secondary to Python -- they ship later, have fewer features, and get less community support. You can call Claude from JavaScript. But when you need to pre-process a CSV, clean text data, build a prompt template from a database query, and post-process the response -- JavaScript makes all of that harder than Python does.

Tip

If Why Python for AI becomes part of a recurring workflow, document the exact trigger, boundary, and verification step now. Future speed comes from clarity, not from memory.

R is excellent for statistics and data visualization. If you're a biostatistician or academic researcher doing classical statistical analysis, R is a strong choice. But R was designed for statistics, not general-purpose programming. It can't easily call web APIs, process files in bulk, or build automation scripts. The AI SDK support for R is minimal to nonexistent. R is a scalpel for statistical analysis; Python is a Swiss Army knife.

SQL is essential for working with databases, and you might learn some alongside Python. But SQL is a query language, not a programming language -- you can't build workflows, call APIs, or process files with it.

Low-code/no-code tools (Zapier, Make, LangFlow) are great for simple automations. But they hit a ceiling fast. The moment you need custom data processing, conditional logic that depends on API responses, or anything the tool's creators didn't anticipate, you're stuck. Python has no ceiling.

Here's the bottom line: Python is the lingua franca of AI. Learning it gives you access to the entire AI ecosystem -- every model, every tool, every research paper with code. No other language comes close.

Map Your Why Python for AI Layers

  1. Open your global, project, and local Claude configuration files.
  2. Write down which rule for this lesson belongs in each layer and why.
  3. Start a fresh Claude Code session and confirm the effective behavior matches your intent.

The "Just Enough Python" Philosophy

Here's something most Python courses won't tell you: you don't need most of Python to do powerful AI work.

Professional software engineers use Python to build web applications, manage infrastructure, create testing frameworks, develop game engines, and architect distributed systems. That's a huge language surface area -- years of study.

You need none of that.

For AI-powered professional work, you need a surprisingly small subset of Python:

Python
# Variables and strings
name = "quarterly_report.pdf"
prompt = f"Summarize this document: {document_text}"

# Lists and dictionaries
files = ["report1.pdf", "report2.pdf", "report3.pdf"]
config = {"model": "claude-sonnet-4-20250514", "max_tokens": 1024}

# Reading files
with open("data.csv", "r") as f:
    content = f.read()

# Loops
for file in files:
    result = process_file(file)
    print(result)

# Conditionals
if response.status_code == 200:
    data = response.json()
else:
    print("Something went wrong")

# Functions
def summarize(text):
    response = client.messages.create(
        model="claude-sonnet-4-20250514",
        max_tokens=1024,
        messages=[{"role": "user", "content": f"Summarize: {text}"}]
    )
    return response.content[0].text

The 'Just Enough' Approach

Do

Learn just enough Python to read files, call APIs, loop over data, and handle results -- then build real tools immediately

Don't

Try to master all of Python first -- decorators, metaclasses, async/await, design patterns -- before touching any AI work

That's it. Variables, strings, lists, dictionaries, file I/O, loops, conditionals, and functions. With these building blocks -- plus a couple of libraries -- you can build genuinely powerful AI tools.

You don't need to understand decorators, metaclasses, generators, async/await, abstract base classes, or design patterns. Those are tools for software engineers building production systems. You're building professional tools that get real work done -- and that requires a fraction of the language.

Think of It Like Driving

You don't need to understand combustion engineering to drive a car. You don't need to understand compiler design to write Python. You need to know the controls -- the steering wheel, gas, and brakes. In Python, those controls are variables, loops, conditionals, functions, and API calls. Master those, and you can go anywhere.

What You'll Build in This Course

This isn't a theoretical course. By the end of the Python for AI track, you'll have built real tools that you can use -- and modify -- in your professional life. Here's a preview:

Project 1: AI-Powered Document Summarizer

You'll write a script that reads any text document, sends it to Claude's API, and returns a structured summary with key points, action items, and a one-paragraph executive brief.

Test a Safe Why Python for AI Override

  1. Add one narrow allow rule and one narrow deny rule related to this lesson.
  2. Ask Claude to trigger both cases in a scratch project or branch.
  3. Note which rule wins and whether the result matches the hierarchy described here.
Python
import anthropic

def summarize_document(filepath):
    with open(filepath, "r") as f:
        text = f.read()

    client = anthropic.Anthropic()
    message = client.messages.create(
        model="claude-sonnet-4-20250514",
        max_tokens=1024,
        messages=[{
            "role": "user",
            "content": f"""Summarize this document. Provide:
            1. A one-paragraph executive summary
            2. Key points (bullet list)
            3. Action items (if any)

            Document:
            {text}"""
        }]
    )
    return message.content[0].text

Project 2: Batch File Processor

You'll build a tool that processes an entire folder of files -- extracting data, transforming it, and saving the results. Imagine processing 200 customer feedback forms in 30 seconds instead of 3 days.

Project 3: Data Analysis Pipeline

Using pandas, you'll load a dataset, clean it, compute statistics, and generate AI-powered insights. You'll combine the analytical power of pandas with the reasoning power of Claude to find patterns a spreadsheet alone would miss.

Capstone: Your Custom AI Tool

The final project is yours to design. You'll identify a real problem in your professional life, architect a solution using the skills from this course, and build it. Past students have built contract clause extractors, patient intake processors, SEO content analyzers, and financial report generators.

Python in the Age of AI Coding Assistants

There's an irony worth addressing: you're learning a programming language at a time when AI can write code for you. Claude, GPT-4, and Copilot can generate Python from natural language descriptions. So why bother learning Python yourself?

Three reasons.

First, you need to read code to use AI-generated code. When Claude writes you a Python script, you need to understand what it does before you run it. Is it reading the right file? Is it sending your data somewhere you don't want? Is the logic correct? You don't need to be able to write every line from scratch -- but you absolutely need to be able to read it, verify it, and debug it when something goes wrong.

Quick Check

What is the main benefit of using Why Python for AI well in Claude Code?

Second, you need to know what's possible to ask for it. If you don't know that Python can read CSVs, call APIs, and process text, you'll never think to ask Claude to build you a data pipeline. Knowledge of Python's capabilities expands your imagination. It lets you see automation opportunities that are invisible to non-programmers.

Third, AI assistants make mistakes. They hallucinate function names, use deprecated APIs, and write code with subtle bugs. The more Python you know, the faster you spot these errors -- and the better your prompts become. The best AI-assisted coders aren't the ones who know the least about programming. They're the ones who know enough to guide the AI effectively.

Think of it this way: learning Python doesn't compete with using AI coding assistants. It makes you dramatically better at using them.

Python
# You'll learn to prompt Claude to write code like this...
# ...and then you'll know enough Python to verify it works

import csv
import anthropic

def analyze_feedback(csv_path):
    """Read customer feedback CSV and generate analysis."""
    client = anthropic.Anthropic()

    with open(csv_path, "r") as f:
        reader = csv.DictReader(f)
        feedback_entries = [row["comment"] for row in reader]

    combined = "\n---\n".join(feedback_entries)

    message = client.messages.create(
        model="claude-sonnet-4-20250514",
        max_tokens=2048,
        messages=[{
            "role": "user",
            "content": f"""Analyze these {len(feedback_entries)} customer
            feedback entries. Identify:
            1. Top 3 themes
            2. Sentiment breakdown (positive/neutral/negative)
            3. Most urgent issues
            4. Recommended actions

            Feedback:
            {combined}"""
        }]
    )
    return message.content[0].text

When you finish this course, you'll look at code like the above and immediately understand what every line does -- what csv.DictReader returns, why we use a list comprehension, how f-strings work, and what the API call is doing. That understanding is what separates someone who can build AI tools from someone who can only use AI chatbots.

Quick Check

After reading this lesson, what should you validate when applying Why Python for AI?


Try It: Your First Python Commands

You don't need to install anything yet -- the next lesson covers installation in detail. But if you already have Python on your machine (many Macs come with it pre-installed), let's run a few commands to see what Python feels like.

Run Your First Python Code

Open your terminal (Mac: search for "Terminal"; Windows: search for "Command Prompt" or "PowerShell") and type:

Bash
python3

(On Windows, try python if python3 doesn't work.)

You should see something like:

Python 3.12.4 (main, Jun  7 2024, 00:00:00)
>>>

That >>> is the Python REPL -- a live interactive environment where you can type Python and see results instantly. Try these commands one at a time:

Python
# Basic math
2 + 2
100 * 365
2 ** 10
Python
# Strings
"Hello, " + "world!"
name = "Python"
f"I am learning {name} for AI"
len("How many characters is this?")
Python
# Lists
tools = ["Claude", "GPT-4", "Gemini", "Llama"]
len(tools)
tools[0]
tools.append("Mistral")
print(tools)
Python
# A tiny taste of what's coming
words = "Python is the language of AI".split()
print(words)
print([w.upper() for w in words if len(w) > 2])

When you're done exploring, type exit() to leave the REPL.

If that worked -- congratulations. You just wrote Python. Notice how little ceremony there was. No boilerplate. No imports (for the basic stuff). No compilation step. You typed a command, and Python responded. That immediate feedback loop is one of the reasons Python is so effective for learning.

Don't Worry If You Don't Have Python Yet

If you don't have Python installed, or if you ran into errors, that's completely fine. The next lesson walks through installation step by step. The exercise above is just a preview -- you'll have plenty of time to get set up.

Map Your Automation Opportunities

This exercise requires no code at all -- just clear thinking about your work.

Grab a piece of paper (or open a notes app) and answer these questions:

  1. List 5 tasks you do at work that involve processing text. These could be reading reports, writing emails, reviewing documents, extracting data from forms, comparing documents, drafting proposals -- anything that involves words and information.

  2. For each task, estimate how long it takes. Be honest. Include the time spent on setup, context-switching, and rework.

  3. Circle the one task that is most repetitive and least creative. This is your automation target -- the task where the steps are predictable, even if the content varies each time.

  4. Describe that task as if you were explaining it to a very capable intern. Write out the steps: "First, open the document. Then find the section about X. Extract the numbers. Compare them to Y. Write a summary paragraph."

That description you just wrote? It's essentially a program. By the end of this course, you'll translate instructions like those into Python code that runs in seconds.

Read Real Python AI Code

Go to github.com/anthropics/anthropic-cookbook and browse the repository. You don't need to understand the code yet. Just notice a few things:

  1. How short most scripts are (often under 50 lines)
  2. How readable the code is -- you can probably guess what many lines do
  3. How much of the work is done by library calls (client.messages.create(...)) rather than raw code

This is the level of Python you're aiming for. Not software engineering. Not systems programming. Just enough code to connect inputs to AI and handle the outputs.


Coming Back to Priya

Remember Priya -- our immigration attorney? There's a detail I left out of her story. When she first opened a Python tutorial, she closed her laptop after 10 minutes. The tutorial started with variables, moved to data types, then spent three pages on the difference between integers and floating-point numbers. It felt abstract. Disconnected. She couldn't see how any of it connected to her actual work.

She came back a week later and tried a different approach. Instead of learning Python from the ground up, she started with a goal: "I want to read a PDF and send its text to an AI." She searched for how to do that specific thing. She found a 15-line example. She copied it, ran it, modified it, broke it, fixed it. Then she wanted to do something slightly different -- process a folder of PDFs -- and she had to learn about loops. Then she wanted to save results to a file, so she learned file I/O. Each concept arrived exactly when she needed it.

30 hrs/week

Time Recovered

Priya's Python scripts saved her 2 hours per case across 15 weekly cases -- nearly an entire second attorney's worth of productive time recovered through code she wrote in a single Saturday.

How confident do you feel about applying Why Python for AI in a real project?

That's how this course is structured. We don't teach Python in the abstract. Every concept is introduced because you need it to build something real with AI. Variables exist so you can store API responses. Loops exist so you can process batches of documents. Functions exist so you can reuse your AI workflows. The language is always in service of the goal.

You don't need a computer science degree. You don't need prior coding experience. You don't need to be "a math person" or "a tech person." You need curiosity, a willingness to experiment, and a real problem you want to solve.

Priya had a stack of visa petitions. You have your own version of that stack -- emails, reports, data, documents, processes that eat your hours. Python is how you start reclaiming them.

In the next lesson, we'll get Python installed on your machine and write your first real script. It takes about 10 minutes. Let's go.

Key Takeaways

  • Python dominates AI because of its readability, massive ecosystem (NumPy, pandas, scikit-learn, PyTorch, Hugging Face), and first-class SDK support from every major AI company
  • You don't need to learn all of Python -- variables, strings, lists, dictionaries, loops, conditionals, functions, and API calls cover 90% of professional AI work
  • Python isn't competing with AI coding assistants -- knowing Python makes you dramatically better at using them, because you can read, verify, and debug generated code
  • Other languages (JavaScript, R, SQL) have their strengths, but none match Python's breadth across data processing, API integration, automation, and AI model access
  • This course teaches Python through building real AI tools -- every concept is introduced when you need it, not before