Python + AI

From a first Python function to a private local chatbot.

  • Eight flexible sessions · roughly 25–35 hours including practice
  • Understand the ideas, learn the tools, build something you can explain

⬇ Download the complete study materials (.zip)

  • Local inference starts in session 5; choose a model that fits your machine.

Roadmap

AI intuition→Python→Dev workflow→Neural networks→Ollama→Streamlit→Quality→Docker
  • Each step produces a thing you can demonstrate
  • Vertical slides contain demos/resources (↓)
  • Skip longer videos in class; use them as homework
  • Course notes: docs/ · example programs: examples/

Download all notes, exercises & slide sources ↗

Course timetable

21 days · 1–2 hours/day · roughly 25–35 hours of core work
DaysCourse focusWhat you can demonstrate
1AI intuitionExplain training vs inference
2–6Mac workbench + PythonUse Terminal + VS Code; build a rule-based chatbot
7–9Developer workflowUse a virtual environment, JSON files and Git
10–12Neural networks + TransformersExplain weights, loss and next-token generation
13–15Local LLMs with OllamaCall a local model from a Python chat client
16–17Web interface with StreamlitBuild browser chat with history and model selection
18–19Product qualityAdd controls, run tests and handle offline errors
20–21Catch-up + graduation; Docker optionalRepeat the demo, change the app and explain it

At 1 hour/day, allow 25–35 study days. Move on when you can explain and modify the exercise. Full day-by-day plan ↗

Your learning track: 21 study days

  • Setup: macOS walkthroughs; adapt commands for other platforms.
  • Time: 1–2 hours per study day; 21 days is a suggested sequence, not a deadline.
  • Language: English for sessions, code and exercises.
  • Model: start with gemma3:4b; later compare to qwen3:8b if useful.

Each day's learning loop

  1. 5–10 min recall and prediction
  2. 15–20 min explanation or visual lesson
  3. 35–65 min programming with the learner at keyboard
  4. 10–20 min independent change and explanation

For a one-hour day, split a topic rather than skipping practice.

macOS setup and daily checklist

01 · What is AI doing?

Rule-based computation vs search/planning vs trained models.

  • A Tetris advisor can use a search algorithm
  • A neural network is a learned function
  • An LLM predicts text tokens using trained parameters
  • A fluent answer is not a correctness guarantee

Inference is not training

Trainingexamples → loss → gradients → updated weights
Inferenceprompt → fixed weights → output tokens

Discuss: Does changing temperature re-train the network? No.

3Blue1Brown · What is a neural network?

Watch ~19 min: neurons, weights, biases, layers.

Open original video ↗ · If the player fails, open the link.

Karpathy · Intro to LLMs (optional)

Start with minutes 00:00–18:00; security section is useful in session 7.

Open original video ↗ · If the player fails, open the link.

Mini-exercise: where does my question go?

Imagine asking a chatbot: “Why is the sky blue?”

Put these three cards in order. You can point or say the answer — no drawing or coding necessary:

  • You — type the question.
  • Chat app — shows messages on screen and sends the question onward.
  • Language model — generates a possible answer.

Try: Which card is first? Which card makes the words? Which card displays them?

Pause and let the beginner order the three cards orally. Do not require knowledge of Python or Ollama yet. Say that this is a simplified view. Show the answer on the next slide and briefly introduce the model server there.

Example answer: follow one message

YOU          CHAT APP             LANGUAGE MODEL
  |  question   |                      |
  +-----------> | --- question ------> |
                | <-- answer --------- |
  <------------ +                      |
     see reply
  • Your action: type “Why is the sky blue?”
  • Chat app: sends it and displays the returned text.
  • Model: produces a plausible explanation, which may need checking.
  • Later: we will learn about Ollama, the program that runs the model on your Mac.

Bonus question: A simple rule-based chatbot could replace the model with if statements. How would its answers differ?

02 · Mac workbench → Python foundations

Before writing the first function, build a real editor + terminal workflow.

  • macOS Terminal.app: window displaying commands and output
  • zsh: shell interpreting commands and remembering history
  • VS Code: editor used to change source code
  • Python: interpreter running saved source files

Four distinct programs, one project

VS Codeopen folder · edit file · ⌘S save
Terminal.appzsh prompt · history · commands
Pythonruns the saved hello.py
Outputread result · debug · edit again ↻

Follow the hands-on Mac workbench lesson ↗

Day 2 — Install editor and prepare Terminal

  • Install Python for macOS and VS Code for Apple Silicon.
  • Open Terminal.app using Spotlight (⌘ Space).
  • Open VS Code → ⌘⇧P → “Shell Command: Install 'code' command in PATH”.
  • Restart Terminal, then try these read-only commands:
uname -m            # native Apple Silicon: arm64
echo "$SHELL"       # usually /bin/zsh
python3 --version
pwd

The optional VS Code Copilot CLI is not required. If code is absent, use File → Open Folder instead. Learners must not modify the system-owned Python.

Open the same folder in both apps

mkdir -p ~/Projects/python-ai-playground
cd ~/Projects/python-ai-playground
code .
  • VS Code File → New Text File, name it hello.py.
  • Type and save (⌘S); back in Terminal run python3 hello.py.
  • If code . fails, choose File → Open Folder in VS Code.

Official VS Code setup for macOS ↗

Two key families (do not mix them)

⌘ Command — Mac application

⌘C copy selected terminal output

⌘V paste at shell prompt / in editor

⌘S save a file in VS Code

⌘T new Terminal.app tab

⌃ Control — zsh / running process

⌃A start · ⌃E end of command

⌃P previous · ⌃N next command

⌃R reverse history search

⌃C interrupt a running command

Learn ⌃A · ⌃E · ⌃P · ⌃N · ⌃R

In the zsh prompt Action
Control-A move cursor to start (A)
Control-E move cursor to end (E)
Control-P previous command (P)
Control-N next command (N)
Control-R reverse search in command history (R)

These act in the terminal shell prompt, not when VS Code's editor has focus.

Two-minute shortcut drill (no copying)

  1. Execute echo APPLES; then echo BANANAS.
  2. Hit ⌃P, again ⌃P, then ⌃N. What changed?
  3. Hit ⌃R, search APPLES, select it.
  4. Type echo hello there without Enter.
  5. Hit ⌃A then ⌃E; press Enter only at the end.

Perform live; keep the cursor visible. In default zsh Emacs-style line editing these bindings are standard. Optional plugins may remap them. Allow mistakes: use the arrow keys to recover, then try again.

Copy + paste is NOT Control-C

  • ⌘C copies selected terminal output; ⌘V pastes it.
  • ⌃C interrupts a program. Test: sleep 30 → ⌃C.
  • ⌃L clears the terminal; Tab attempts completion.
  • Select text with trackpad; copy into VS Code with ⌘C/⌘V.
  • Copy the command below into Terminal, inspect it, then press Enter.
printf 'Pasted safely into the terminal\n'

Never blindly paste multiline commands or run unknown curl | sh installers.

Apple's Terminal shortcut reference ↗

Day 2 checkpoint — edit → save → run → debug

In VS Code create hello.py and type:

name = "friend"
print(f"Hello, {name}!")
  • ⌘S save. Terminal: python3 hello.py.
  • Change friend to your name → ⌘S → ⌃P → Enter.
  • Break a quote deliberately. Read the error. Fix it.
  • Copy output (⌘C), paste into a scratch note (⌘V).

Check: Can you explain which app each key affected?

Python first steps

def respond(message: str) -> str:
    text = message.lower().strip()
    if "hello" in text:
        return "Hello!"
    if text.endswith("?"):
        return "I don't know yet."
    return "Tell me more."

print(respond("Hello there"))

Independent change: detect three additional phrases.

CS50P lecture & PDF

Harvard CS50's Introduction to Programming with Python · Week 0: functions and variables.

Open 32-page PDF ↗ · Current lecture page ↗ · Lecture video ↗

Session 2 exercise

  1. Create a message loop; quit when input is quit
  2. Explain the difference between print and return
  3. Test the greeting, unknown question, and empty input
  4. Change one feature without an AI coding assistant

03 · Developer workflow (on macOS)

Now that you can edit, save and run, learn to manage a project:

  • Terminal: paths, directories, running programs
  • Editor: read a traceback before searching for solutions
  • python -m venv: isolate project packages
  • JSON: load and save structured data
  • Git: record what changed

Day 7 — isolated Python environment

In Terminal.app, create a separate project for experimenting:

mkdir -p ~/Projects/prompt-library
cd ~/Projects/prompt-library
python3 -m venv .venv
source .venv/bin/activate
python -m pip --version
code .
  • VS Code edits; the terminal runs. .venv/ stays out of Git.
  • Leave this shell configured until finished with this little project.

Native zsh first; z4h is an optional extra

  • macOS already includes zsh — no framework required.
  • Zsh for Humans (z4h) ↗ works on macOS and adds autosuggestions, completions and fuzzy history.
  • Its maintainer states support is very limited; most bugs will go unfixed.
  • Its installer changes shell startup files (with backup prompts).
  • Do not install automatically or teach shell shortcuts through z4h first.

Introduce only after the Control-A/E/P/N/R drill and getting comfortable in stock zsh. Discuss tradeoffs, original README, backups, rollback. Do not pipe a remote script into a shell for a beginner.

MIT Missing Semester

Choose only: shell, debugging, Git. No need for every lecture.

Read HTML in browser, Markdown in your editor

  • Click a lesson in these slides to open the formatted HTML reading view.
  • Each HTML lesson offers Original Markdown (.md) to download or view.
  • On Day 7, use the terminal to download a data file, then open in VS Code:
cd ~/Projects/python-ai-playground
curl --fail --location --show-error \
  --output lesson.md \
  https://study.fkr.dev/docs/01-ai-intuition.md
code lesson.md

Safety: curl saves the lesson; never pipe unknown downloads into sh.

Days 8–9 — one reproducible project

  1. In VS Code, save JSON prompt presets and a reader function.
  2. Run it in Terminal; recall the command with ⌃P, search with ⌃R.
  3. Create a deliberate error and read its traceback.
  4. In ~/Projects/prompt-library, git init, git status, then commit source.
  5. Explain why .venv/ and secrets should not be committed.

Detailed macOS + Git lab ↗

04 · Neural networks

The intuitive chain:

  • Loss: how wrong were the predictions?
  • Gradient: how do changes affect the loss?
  • Backpropagation: how we efficiently compute those gradients
  • Optimization: how parameters are updated

Gradient descent · 3Blue1Brown

~21 min · What training means in practice.

Open original video ↗ · If the player fails, open the link.

Backpropagation, intuitively

~14 min · The gradients come from propagating sensitivity backward.

Open original video ↗ · If the player fails, open the link.

Neural Network Playground

Live exercise: vary layers, learning rate and noise. Compare training and test loss.

Transformers · 3Blue1Brown

~27 min · Tokens, embeddings, attention and next-token prediction.

Open original video ↗ · If the player fails, open the link.

Transformer Explainer

Interact with a small GPT-2 model in-browser and inspect probable next tokens and attention.

05 · Local inference with Ollama

You need a model, a runtime/server, and a Python client.

Python (ollama client)
   │ HTTP /api/chat
   ▼
Ollama (inference runtime)
   │ loads quantized model weights
   ▼
Local model (CPU or GPU)

First Ollama call

cd ~/Projects/py-ai-studyplan
source .venv/bin/activate  # create .venv first if absent
ollama pull gemma3:4b
ollama run gemma3:4b
# In another Terminal tab (⌘T):
cd ~/Projects/py-ai-studyplan
source .venv/bin/activate
python -m pip install -r examples/requirements.txt
python examples/cli_chat.py --model gemma3:4b

Choose a model for your machine

  • Examples use gemma3:4b; check available memory and disk first.
  • Compare with qwen3:8b later (optional).
  • Use gemma3:1b only if the larger model is too slow or unavailable.
  • Unified RAM is shared with macOS: file size ≠ runtime memory use.
  • An LLM is not necessary to practice writing and debugging Streamlit controls.

Official Ollama resources

06 · Build a web interface

Streamlit makes a first browser UI possible without teaching JavaScript.

  • st.chat_input · user question
  • st.chat_message · display turns
  • st.session_state · keep app state across reruns
  • Python Ollama client · inference request
  • Friendly offline/error messages

Architecture

Browser → Streamlit server → Ollama HTTP API
               │                  │
         chat history          model weights
               │                  │
         UI rendering ◀──── generated response

Run your chatbot

cd ~/Projects/py-ai-studyplan
source .venv/bin/activate
python -m pip install -r examples/requirements.txt
# Ollama desktop app is already running and model pulled.
python -m streamlit run examples/chat_app.py --server.address 127.0.0.1

Observe: when you stop Ollama, Python can still display the web UI but cannot serve model completions.

Official Streamlit tutorial

Stretch tasks

  • Baseline app: model picker, clear history, temperature, JSON export.
  • Your changes: add a system prompt preset and report the difference.
  • With Ollama stopped, show a friendly error, not a crash.
  • Explain why edited code must be saved before rerunning.

07 · Make it useful

  • Structured output must be parsed and validated
  • Models can make arithmetic/factual mistakes
  • Treat model text as untrusted data
  • Handle Ollama offline, missing models, and invalid responses
  • Measure behavior with a tiny repeatable test set

Evaluation exercise

Input type Test
Exact format Is JSON parseable and schema-valid?
Arithmetic Verify with ordinary Python
Summarization Check facts against original
Failures Stop Ollama and observe feedback
Compare models Record model, settings, latency

Karpathy · Prompt injection & security

Optional segment near 45:40. Ask: why can't we trust instructions inside model outputs?

Open original video ↗ · If the player fails, open the link.

08 · Docker

Pack the web UI after it works locally.

  • Dockerfile → reproducible image
  • Container → process started from the image
  • Ports → how the browser reaches the app
  • Environment variables → configuration
  • Compose → coordinate one or more services

Build and launch (optional)

docker build -t py-ai-studyplan-ui ./examples
docker compose -f examples/compose.yaml up --build
docker compose -f examples/compose.yaml down

Docker-internal 127.0.0.1 is not host-localhost. Keep Ollama private; the UI can demonstrate its offline fallback in a container.

Docker official guides

Two graduation projects

Project A · Local LLM playground

Must-have:

  • Start a model, send a prompt, render a response
  • Preserve and clear chat history
  • Explain each process and HTTP boundary
  • Fail gracefully if model is unavailable
  • Reproduce setup from the README

Project B · Classical Tetris AI (optional)

  1. Represent a board and valid piece placements
  2. Score lines, holes, height and bumpiness
  3. Search legal placements and choose a move
  4. Compare to random moves on fixed seeds
  5. Optional LLM explains the chosen move

A Tetris solver is primarily a search/planning lesson. Do not imply that an LLM inherently solves Tetris.

Final review

Can they independently:

  1. Write a simple Python function and a test?
  2. Explain training vs inference and tokens?
  3. Show Python → Ollama → browser?
  4. Debug an HTTP or model error?
  5. Recreate the development environment?
  6. Explain image vs container and why public API exposure is unsafe?

Success is understanding and modifying the system — not copying a chatbot.

Learning resources

Full curated catalog: docs/resources.md (also linked from the project README).