SproutStackSproutStack home

Python Essentials for AI

8 min readBeginner-friendlyFree to read

Read a little, play a little. No scary maths, and no rush.

Share:

The 20% of Python that runs 80% of AI apps

You don't need decorators, metaclasses, or the descriptor protocol to build AI apps. You need variables, functions, lists and dicts, file I/O, f-strings, and package hygiene. Everything in this track — RAG chunkers, API loops, eval harnesses — is built from these bricks.

The crash kit, annotated

names = ["rag", "agents"]            # lists: ordered collections
cfg = {"model": "gpt-4o-mini", "k": 4}  # dicts: configs, JSON, API shapes

def chunk(text, n=200):              # functions: name the job
    return [text[i:i+n] for i in range(0, len(text), n)]  # comprehension

with open("docs.txt") as f:          # files: always use `with`
    docs = f.read()

print(f"loaded {len(docs)} chars, {len(chunk(docs))} chunks")  # f-strings

Dicts deserve special attention: JSON is dicts-and-lists, LLM messages are dicts, configs are dicts. If dicts feel native, APIs feel native.

Environment hygiene (boring, essential)

  • venv per project: python -m venv .venv — dependencies for project A never fight project B.
  • Pin it: pip freeze > requirements.txt so teammates (and future-you, and deploy servers) install the same universe.
  • Secrets in env: os.getenv("OPENAI_API_KEY") — never in code, never in git.

Reading a traceback, step by step

When Python crashes it prints a traceback: the chain of calls that led to the error, oldest at the top and the failure at the bottom. Beginners read it top-down and drown. Read it bottom-up instead.

Traceback (most recent call last):
  File "app.py", line 12, in <module>
    print(cfg["temperature"])
KeyError: 'temperature'
  1. Last line first. KeyError: 'temperature' means your code looked up a key the dict does not have.
  2. Find your own file. The line just above it, app.py, line 12, is where it happened. Lines inside installed libraries are usually not where the mistake is.
  3. Ask what value surprised you. Here, cfg was built without a "temperature" key. Use cfg.get("temperature", 0.2) or add the key.

A few errors cover most beginner crashes. KeyError is a missing dict key. TypeError: 'NoneType'... means something you expected to hold a value was None, often a function that forgot to return. ModuleNotFoundError usually means the virtual environment is not activated. IndentationError means the spacing is inconsistent.

The fluency checklist

f-strings, list/dict comprehensions, requests.get/post, json.loads/dumps, os.getenv, slicing (text[i:i+n]), and reading tracebacks calmly. If those are comfortable, every later chapter's code will read like prose.

If you can read/write files, call APIs, and loop dicts, you can build AI apps.

Putting it together: a tiny real task

Most AI projects start with unglamorous data preparation, and it uses exactly the skills above. Suppose you have a folder of text notes and want them as one clean file for a retrieval system:

import json
from pathlib import Path

rows = []
for path in Path("notes").glob("*.txt"):
    text = path.read_text(encoding="utf-8").strip()
    if text:                                   # skip empty files
        rows.append({"source": path.name, "text": text})

with open("notes.jsonl", "w", encoding="utf-8") as f:
    for row in rows:
        f.write(json.dumps(row) + "\n")
print(f"wrote {len(rows)} notes")

Files, a loop, a dict per note, JSON out, and an f-string to report. Each line of this file (JSONL) is one record, which is the format many AI tools expect.

Three habits that save hours

  • Look before you transform. Before reshaping data, print what you actually have: type(x), len(x), and the first item. Most "mysterious" bugs are a list where you expected a dict, or a string where you expected a number.
  • Keep functions small and named for their job. clean_text, split_into_chunks, and save_rows are easy to test one at a time. One 80-line function that does all three is not.
  • Experiment in a REPL or notebook, then move to a file. Try an idea interactively until it works, then copy the working version into a script you can rerun and commit.

Remember this

  • Lists order, dicts name. Comprehensions compress loops. venvs prevent wars.
  • Tracebacks are instructions, not insults — read the last line first.

Check your understanding

5 questions · first-try answers earn the most XP

1. Why do AI configuration files and API payloads map so naturally onto Python dicts?
2. What is a virtual environment for in a Python project?
3. Why is reading a traceback calmly a listed skill rather than an afterthought?
4. Where should an API key live in a Python project?
5. What does pinning dependencies with a requirements file protect you from?

My notes

Saved in this browser. Highlight a line above and save it, or write it in your own words.

Nothing saved yet. Your highlights will live here.

References

Finished reading?

Ticking it here also ticks the chapter in the sidebar, the section count and your streak — it is all one number.

Related chapters

Spotted a mistake or want a topic covered? Report an issue

📬 An occasional email when new lessons land

New lessons and showdowns, no more than a few times a month. No spam, unsubscribe anytime. We store your email only to send the newsletter.