What Is Code?
By the end of Phase 1, you can read a 30-line Python function and explain what it does. See the Phase 1 Gate for the exact test.
Chapter 01 What Programming Actually Is
Before you can judge whether AI-generated code is good or bad, you need to know what code is. This chapter gives you the mental model that makes everything else in the curriculum click.
Programming is writing instructions for a machine that has zero common sense. Imagine telling someone to make a peanut butter sandwich. A human grabs the jar, opens it, picks up a knife. A computer? It stares at the sealed jar because you didn't say "open the jar." Every instruction must be explicit, literal, and in order.
A program is a text file containing these instructions. Not a mysterious binary blob—a plain text file you can open in any editor. An interpreter (for languages like Python) or a compiler (for languages like Rust) translates your human-readable text into instructions the machine's processor can execute.
Why Code Exists
Computers understand one thing: voltage patterns. High voltage = 1. Low voltage = 0. That's it. Programming languages exist so humans don't have to think in ones and zeros. Between the Python you write and the voltages flipping in the CPU, there are several translation layers—and you never need to touch the lower ones.
The Language Landscape
Different programming languages exist for different jobs, the same way you'd use a screwdriver for screws and a hammer for nails. Here are the major categories:
What Software Actually Looks Like
The diagram above shows language categories. But what are the things people build with them? Almost all software falls into a few major categories—and most real products combine several.
Web Systems (Frontend + Backend)
A web application is anything you use in a browser: Gmail, YouTube, GitHub, online banking. It has two halves:
- Frontend — what you see. HTML structures the page, CSS styles it, JavaScript makes it interactive. When you click a button and a menu appears without the page reloading, that's JavaScript running in your browser.
- Backend — what you don't see. A server (often written in Python, Node.js, Go, or Rust) processes requests, enforces business rules, and talks to a database. When you log in, the backend checks your password. When you post a comment, the backend saves it.
The frontend and backend communicate over HTTP—the same protocol you'll learn in Chapter 13. Every URL you visit triggers an HTTP request to a backend somewhere.
Real example: Twitter/X. The frontend renders your timeline in the browser. The backend handles authentication, stores tweets in a database, runs the recommendation algorithm, and serves the timeline data as JSON over HTTP. Millions of users, thousands of backend servers, one seamless experience.
Mobile Applications
Apps on your phone. Two approaches:
- Native apps — built specifically for one platform. Swift for iOS, Kotlin for Android. Best performance, full access to device hardware (camera, GPS, sensors). Instagram, the iOS Calculator, and Apple Health are native.
- Cross-platform apps — one codebase, both platforms. React Native (JavaScript) or Flutter (Dart) generate iOS and Android versions from the same code. Faster to develop, slightly less polished. Many startups use this.
Most mobile apps still need a backend—they're just a different frontend talking to the same kind of server over HTTP.
Databases
A database is organized, persistent storage. Without one, your data disappears when the program stops. There are two main families:
- Relational (SQL) — data in tables with rows and columns, like a spreadsheet with strict rules. PostgreSQL, MySQL, SQLite. Best when data has clear relationships (users have orders, orders have items). You'll use SQLite in Chapter 15.
- Non-relational (NoSQL) — flexible structures: documents (MongoDB), key-value pairs (Redis), or graphs (Neo4j). Best for unstructured data, caching, or relationships that don't fit neatly into tables.
Real example: An e-commerce site like Shopify uses a relational database for products, orders, and customers (structured, relational data). It might use Redis (NoSQL) for caching product pages so they load instantly, and a search engine like Elasticsearch for product search.
How They Fit Together
A modern application typically combines all three. Consider a ride-sharing app like Uber:
- Mobile app (frontend) — shows the map, lets you request a ride, displays the driver's location in real time
- Backend servers — match riders to drivers, calculate pricing, process payments, handle surge pricing logic
- Databases — store user profiles, trip history, payment methods, driver ratings
- Web dashboard — lets drivers manage their account, lets admins monitor the system
This curriculum focuses on Python backends and SQLite databases because that's the foundation. Once you understand how a backend processes requests and stores data, everything else—frontends, mobile apps, cloud infrastructure—is a variation on the same patterns.
Common Misconceptions
Programming is closer to writing recipes than solving equations. Most code is about organizing information and describing processes, not calculus. The math-heavy work (machine learning, physics simulations) is a specialization, not a prerequisite.
A program is a text file. You can open taskforge.py (the project you'll build in this course) in Notepad and read every line. There's nothing hidden. Later, when AI generates code for you, remembering this keeps you grounded—it's just text you can read and judge.
Micro-Exercise 1
Open any browser. Press F12 (or right-click → Inspect). Click the Console tab. Type the following and press Enter:
The browser concatenated (joined) two text strings. You just gave the machine an instruction and it followed it literally. It didn't "understand" what hello and world mean—it glued two pieces of text together because you told it to.
Micro-Exercise 2
In the same console, type 2 + 2 and press Enter. Now type "2" + "2" (with quotes). Why are the results different?
Answer: 2 + 2 adds numbers (result: 4). "2" + "2" concatenates strings (result: "22"). The quotes change the data type—the machine takes you literally.
Where TaskForge Fits
Throughout this course, you'll build TaskForge—a command-line task manager. It starts as a 40-line Python file and grows into a multi-agent project by Phase 5. Right now, just know: TaskForge is a text file containing instructions. By the end of this chapter, you already know what that means.
Open any browser. Press F12. Click Console. Type the following two lines, pressing Enter after each:
Verification: If the console shows 4 and then I wrote code, you succeeded. You just executed a program that produces output.
If this doesn't work: If F12 doesn't open developer tools, try right-click → Inspect → Console tab. On Safari, enable the Developer menu first (Settings → Advanced → Show features for web developers).
Interactive Exercises
The exercises below run Python directly in your browser using a technology called Pyodide (Python compiled to run inside a web page). No extra install needed. Let's test it right now:
Hello Python in Your Browser
Type print(2 + 2) on the first line and print('Hello, world!') on the second. Click Run to see the output, then Check to verify.
If you clicked Run and nothing happened, or you see "Failed to load Python runtime," your browser is blocking Pyodide from loading. This happens in some browsers when you open an HTML file directly (when your address bar shows file:///). The fix is to serve these files through a local web server—a tiny program that runs on your computer and hands files to your browser the same way a real website would. It sounds complicated, but it's one terminal command. Follow the steps below, and every exercise in the entire guide will work.
If the exercise did work, skip this section entirely and continue to the next exercise.
How to start a local server (click to expand)
Step 1: Open your terminal
- Mac: Press Cmd + Space, type Terminal, press Enter.
- Windows: Press Win + R, type cmd, press Enter. (Or search for "Command Prompt" in the Start menu.)
- Linux: Press Ctrl + Alt + T.
Step 2: Navigate to the folder containing these files
You need to tell the terminal where the HTML files are. Use the cd (change directory) command followed by the path to the src folder. For example:
Replace the path with wherever you actually saved these files. If you're not sure, find the src folder in your file explorer, then:
- Mac: Right-click the
srcfolder, hold Option, click "Copy ‘src’ as Pathname." Then typecdin the terminal and paste. - Windows: Click the address bar in File Explorer, copy the path. Then type
cdin the terminal and paste.
Step 3: Start the server
Type this command and press Enter:
Let's break down what each piece means, because nothing here should feel like magic:
python3— This runs the Python program you installed in Chapter 01. It's the same Python you'll write code in later.-m— This flag tells Python: "run a built-in module (a mini-program that comes pre-installed with Python) by name." You don't need to download anything extra. Think of-mas "run module."http.server— This is the name of the built-in module. It turns your computer into a tiny web server. A server is just a program that waits for requests and sends back files—the same thing that happens when you visit any website. The difference is that this server runs on your computer and only you can access it.8000— This is the port number. Think of your computer as a building with thousands of numbered doors. Port 8000 is the door you're telling the server to listen on. The number 8000 is a common convention for local development—it could be almost any number, but 8000 is what most tutorials use, so we'll stick with it.
What you should see: After pressing Enter, the terminal will print something like:
This means the server is running and waiting. Your terminal will look like it's "stuck"—that's normal. It's not stuck; it's listening for requests. You won't be able to type more commands in that terminal window while the server is running. (That's expected. You'll stop it later with Ctrl + C.)
If python3 doesn't work:
- Windows: Try
python -m http.server 8000instead (Windows often installs Python aspythonwithout the3). - "command not found" error: Python isn't installed yet, or it's not in your system's PATH. Go back to the Python installation step at the start of this chapter and try again. On Mac, you can also try
python3 --versionto check if Python is installed. - "Address already in use" error: Another program is using port 8000. Try a different port number:
python3 -m http.server 8080. If you use a different port, replace8000with your port number in Step 4.
Step 4: Open in your browser
Leave the terminal running (the server needs to stay on). Open a web browser—Chrome, Firefox, Safari, or Edge all work—and type this into the address bar (the bar at the very top where URLs go, not the search bar):
Let's break this down too:
http://— This tells the browser to use the HTTP protocol (the same one every website uses).localhost— This is a special name that means "this computer." Instead of going out to the internet, the browser talks to the server you just started on your own machine.:8000— This is the port number from Step 3. It tells the browser which "door" to knock on.
What you should see: A plain-looking page listing all the files in the src folder (like phase-1.html, phase-2.html, etc.). Click phase-1.html to return to this page—now the interactive exercises will work.
How to tell it's working
Look at your browser's address bar. It should say http://localhost:8000/phase-1.html. If it still says file:///..., that means you opened the file directly instead of through the server—go back to Step 4 and type the localhost address.
When you're done
Go back to the terminal window where the server is running and press Ctrl + C (hold the Control key and press C). This sends a "stop" signal to the server. You'll see the terminal return to normal, ready for new commands. The exercises will stop working in the browser once the server is off—that's expected.
Next time you want to use the exercises, repeat Steps 2–4. It takes about 10 seconds once you've done it a few times.
Knowledge Check
Which of these is NOT a programming language?
Chapter 02 How Computers Execute Code
When Claude Code generates a function, you need to trace it in your head: what goes in, what changes, what comes out. This chapter teaches you how the machine thinks—literally, step by step.
Now that you know a program is a text file with instructions, let's see how the machine actually runs those instructions. The key idea: sequential execution—the computer reads your code top to bottom, one line at a time, in the exact order you wrote it.
Variables: Labeled Boxes
A variable is a labeled box that holds a value. Think of a row of mailboxes in an apartment building: each has a name on it, and you can swap out what's inside without changing the label. In Python, you create one with the = sign:
# This is Python — the language we'll use throughout this guide
speed = 85
name = "TaskForge"
running = True
The label (speed) stays. The value inside can be replaced. speed = 90 puts a new value in the same box—the old 85 is gone.
Data Types: Box Shapes
The type of a value determines what operations are valid:
| Type | Example | What It Is |
|---|---|---|
| Integer | 42 | Whole number |
| Float | 3.14 | Decimal number |
| String | "hello" | Text (always in quotes) |
| Boolean | True / False | Yes or no |
Operators and Expressions
Now that you have values in boxes, you need to combine them. An expression is any piece of code that produces a value. 2 + 3 is an expression that produces 5.
Arithmetic Operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Add (or concatenate strings) | 3 + 4 | 7 |
- | Subtract | 10 - 3 | 7 |
* | Multiply | 5 * 6 | 30 |
/ | Divide (always returns a float) | 10 / 3 | 3.333... |
// | Integer division (rounds down) | 10 // 3 | 3 |
% | Remainder (modulo) | 10 % 3 | 1 |
** | Exponent (power) | 2 ** 3 | 8 |
price = 29.99
quantity = 3
total = price * quantity # 89.97
print(total)
Note: + works differently depending on the type. 3 + 4 adds numbers. "hello" + " world" joins strings. Mixing types ("3" + 4) causes a TypeError—the machine takes you literally.
Micro-Exercise 3
Before running this, predict the value of result:
a = 17
b = 5
result = a // b
remainder = a % b
print(result, remainder)
Answer: 3 2 — 17 divided by 5 is 3 with remainder 2. Integer division (//) drops the decimal, and modulo (%) gives the leftover.
Errors as Feedback
When your code goes wrong, the computer tells you—if you know how to listen. There are three types of errors:
When AI tools like Claude Code generate code, they almost never produce syntax errors (Type 1) or runtime crashes (Type 2). The dangerous failures are logic errors—code that runs perfectly but produces the wrong result. This is why you need to understand what the code should do, so you can catch what the AI got wrong.
Micro-Exercise 1
Before running this, write down what you think b will be:
a = 3
b = a
a = 7
print(b)
Answer: 3, not 7. When b = a ran, b got a copy of a's value at that moment. Changing a later doesn't affect b.
Micro-Exercise 2
name = 'world'
print('Hello, ' + name + '!')
Answer: Hello, world! — string concatenation joins the three pieces.
Predict the output of these three snippets before running them. Write your predictions down, then verify:
Verification: If you predicted 20, python, and an error (ZeroDivisionError), you understand sequential execution, string concatenation, and runtime errors.
If this doesn't work: If Python isn't installed yet, do Chapter 03 first, then return. Or use the browser console at replit.com (free, no install needed).
TaskForge Connection
In TaskForge v0.1, the line task = {"id": len(tasks) + 1, "description": description, "status": "pending"} uses every concept from this chapter: a variable (task), integers (len(tasks) + 1), strings ("pending"), and assignment (=). By the time you read that code in Chapter 04, these will be familiar patterns.
Interactive Exercises
Predict Then Verify
Before clicking Run, predict what each line will print. Then run the code and compare your predictions.
Variable Swap
You have two variables a and b. Swap their values so that a ends up with b's original value and vice versa. Use only variables and assignment—no functions, no built-in tricks.
If you just write a = b, you lose a's original value. You need a temporary box to hold it first.
Create a third variable: temp = a, then a = b, then b = temp.
Knowledge Check
After running a = 3; b = a; a = 7, what is the value of b?
Chapter 03 Setting Up Your Environment
Every AI coding tool—Claude Code, Cursor, Copilot—runs in a development environment. If your environment isn't set up, nothing else in this curriculum works. This is the chapter that makes your machine ready.
Before you can run Python code, you need two things: a terminal (where you type commands) and Python (the interpreter that runs your code). This chapter gets both working.
The Terminal
The terminal is a text-based interface to your computer. Instead of clicking File → New Folder, you type mkdir new_folder. It's faster, scriptable, and—crucially—it's how every AI coding tool works. Claude Code runs entirely in the terminal.
Upgrading Your Terminal Emulator
A terminal emulator gives you a window into your shell. The shell is the program that interprets your commands (bash, zsh); the terminal emulator is the application that displays the shell and handles input. Every OS ships a default one, but third-party terminal emulators add features like split panes, search, and instant replay that make a meaningful difference once you're spending hours in the terminal daily.
macOS: iTerm2 (free, from iterm2.com). Split panes, paste history, instant replay, infinite scrollback. The terminal upgrade that pays for itself within a week of daily use.
Windows: Windows Terminal (pre-installed on Windows 11, free from Microsoft Store on Windows 10). Supports tabs, split panes (Alt + Shift + D), and profiles. This is the modern default—do not use the legacy cmd.exe.
Linux: Alacritty or Kitty (both free, GPU-accelerated, config-file-based). Install via your package manager.
When you're running Claude Code in one pane, watching test output in another, and tailing a log in a third—all at the same time—you'll understand why a better terminal matters. iTerm2 handles this natively. The default Terminal does not.
Installing iTerm2
After installing, open iTerm2 and make it your default: iTerm2 → Make iTerm2 Default Term (in the menu bar).
Essential iTerm2 Configuration
Open Preferences (Cmd + ,) and apply these settings:
| Setting | Where | What to Change |
|---|---|---|
| Infinite scrollback | Profiles → Terminal | Check "Unlimited scrollback." Without this, long command output gets lost. |
| Reuse previous directory | Profiles → General → Working Directory | Select "Reuse previous session's directory." New tabs open where you already are. |
| Natural text editing | Profiles → Keys → Key Mappings | Click Presets → Natural Text Editing. This lets Option+Arrow move word-by-word, like every other macOS app. |
| Font | Profiles → Text | Set to JetBrains Mono or MesloLGS NF at 13-14pt. Monospace fonts make code alignment visible. |
| Color scheme | Profiles → Colors | Click Color Presets → choose Solarized Dark or Tango Dark. Default is too low-contrast. |
iTerm2 Hotkeys You'll Use Daily
| Hotkey | Action | Why It Matters |
|---|---|---|
Cmd + D | Split pane vertically | Code on the left, tests on the right. Or Claude Code left, log output right. |
Cmd + Shift + D | Split pane horizontally | Stack panes top/bottom. Good for watching multiple logs. |
Cmd + ] / Cmd + [ | Cycle between panes | Move focus without touching the mouse. |
Cmd + Option + Arrow | Move to specific pane | Jump directly left/right/up/down to the pane you want. |
Cmd + T | New tab | Separate contexts: one tab per project. |
Cmd + W | Close tab/pane | Clean up when done. |
Cmd + 1/2/3 | Switch to tab 1/2/3 | Jump between projects instantly. |
Cmd + Shift + H | Paste history | Browse everything you've copied. Searchable. |
Cmd + F | Find in terminal output | Search through scrollback for errors, URLs, or specific output. |
Cmd + Shift + Enter | Maximize/restore pane | Temporarily full-screen one pane, then restore the split. |
Cmd + / | Show cursor position | When you lose the cursor in a wall of text. |
Cmd + Option + B | Instant replay | Scrub back through terminal history like a video. See output that scrolled past. |
Windows: Use Windows Terminal (pre-installed on Windows 11, free from Microsoft Store on Windows 10). It supports tabs, split panes (Alt + Shift + D), and profiles. Linux: Use Alacritty (GPU-accelerated, config-file-based) or Kitty (fast, with built-in splits). Both install via your package manager.
Terminal Speed: Shell Hotkeys
These work in any terminal—iTerm2, default Terminal, Windows Terminal, Linux. They use readline keybindings, which are the same across bash and zsh. Learn these and you'll never reach for the mouse while typing commands.
| Hotkey | Action | Example Use |
|---|---|---|
Ctrl + A | Jump to beginning of line | Typed a long command and need to add sudo at the start. |
Ctrl + E | Jump to end of line | Back to the end after editing the beginning. |
Ctrl + W | Delete word backwards | Erase the last argument without hitting backspace 20 times. |
Ctrl + U | Delete from cursor to start of line | Clear a half-typed command and start over. |
Ctrl + K | Delete from cursor to end of line | Keep the command name, erase all arguments. |
Ctrl + Y | Paste last deleted text | Restore what Ctrl + U or Ctrl + W deleted. |
Ctrl + R | Reverse search history | Type part of a past command and it autocompletes from history. The single biggest time saver. |
Ctrl + C | Cancel current command | Kill a running process or abandon a half-typed line. |
Ctrl + D | Exit / send EOF | Close the current shell session (same as typing exit). |
Ctrl + L | Clear screen | Clean slate without losing history. Same as clear but faster. |
Ctrl + Z | Suspend process | Pause a running process. Resume with fg. |
Option + Left/Right | Move word by word | Navigate through arguments quickly (requires Natural Text Editing in iTerm2). |
!! | Repeat last command | sudo !! re-runs the last command with sudo. |
!$ | Last argument of previous command | mkdir new-dir && cd !$ creates and enters the directory. |
Tab | Autocomplete | Type the first few letters of any file/command and Tab completes it. Double-Tab shows all options. |
Up/Down Arrow | Navigate command history | Scroll through previous commands. Combine with Ctrl + R for power searching. |
Type this long command but don't press Enter: python3 -m pytest tests/ -v --tb=short. Now practice: Ctrl + A (jump to start), Ctrl + E (jump to end), Ctrl + W (delete last word), Ctrl + U (delete everything), Ctrl + Y (paste it back). Do this 5 times until it's muscle memory.
Installing Python
| OS | Install Command | Verify |
|---|---|---|
| macOS | brew install python3 or download from python.org | python3 --version |
| Windows | Download from python.org — check "Add to PATH" | python --version |
| Linux | sudo apt install python3 | python3 --version |
The REPL
Type python3 in your terminal. The >>> prompt appears—this is the REPL (Read-Eval-Print Loop). It's your sandbox: type any Python expression, see the result instantly. Type exit() to leave.
Your First File
Create a file called hello.py containing one line:
print("Hello, World!")
Run it: python3 hello.py. The terminal prints Hello, World!. That's it—you've written and executed a program.
Virtual Environments
Before you install any Python packages, you need to understand virtual environments. A virtual environment is a self-contained copy of Python for a specific project. Without one, every package you install goes into a single global location—and eventually, two projects will need different versions of the same package. Things break. Virtual environments prevent this entirely.
pip installNever run pip install outside a virtual environment. If you install packages globally, they pile up, conflict, and eventually something breaks in a way that's hard to diagnose. A virtual environment keeps each project's packages isolated.
Creating a Virtual Environment
This creates a .venv folder inside your project. It contains a private copy of Python and a clean, empty set of packages. The folder name .venv is a convention—the dot makes it a hidden folder so it doesn't clutter your file listing.
Activating the Virtual Environment
How to Tell You're in a Virtual Environment
Two clues tell you it worked:
# 1. Your prompt changes — you'll see (.venv) at the beginning:
(.venv) ~/my-project $
# 2. which python points to the venv, not the global Python:
(.venv) ~/my-project $ which python
/Users/you/my-project/.venv/bin/python
Deactivating
When you're done working on a project, type deactivate to return to the global Python:
The (.venv) prefix disappears from your prompt, and which python points back to the system Python.
Micro-Exercise 3
Run each line one at a time. After each command, read what the terminal prints before moving on.
Verification: After step 4, the path should include .venv/. After step 5, you should see only pip and setuptools. After step 7, the path should be different from step 4 (it's your system Python again). If all three match, you've got it.
Your Code Editor
You can write code in any text editor, but a code editor highlights syntax, catches typos, and integrates with the terminal. Start with VS Code (free, from code.visualstudio.com). AI-native editors like Cursor and Windsurf build AI assistance directly in—you'll use these in Phase 4.
VS Code Hotkeys That Save Real Time
These are the shortcuts professionals use constantly. On macOS, Cmd = ⌘. On Windows/Linux, replace Cmd with Ctrl.
| Hotkey | Action | Why It Matters |
|---|---|---|
Cmd + P | Quick Open file by name | Type part of a filename to open it instantly. Never use the file tree for known files. |
Cmd + Shift + P | Command Palette | Every VS Code action is searchable here. "Format document," "Toggle terminal," "Change language mode." |
Cmd + ` | Toggle integrated terminal | Switch between editor and terminal without leaving VS Code. |
Cmd + B | Toggle sidebar | Hide/show the file explorer to get more editor space. |
Cmd + D | Select next occurrence | Select a word, hit Cmd + D repeatedly to select and edit all instances at once. |
Cmd + Shift + K | Delete entire line | Remove a line without selecting it first. |
Option + Up/Down | Move line up/down | Rearrange code without cut-and-paste. |
Cmd + Shift + F | Search across all files | Find every usage of a function or variable in the entire project. |
Cmd + / | Toggle comment | Comment/uncomment the current line or selection. |
Cmd + Shift + \\ | Jump to matching bracket | Navigate nested code blocks quickly. |
Ctrl + G | Go to line number | Jump directly to line 142 when an error message says "line 142." |
F12 | Go to Definition | Jump to where a function is defined. Cmd + Click does the same thing. |
Cmd + Z / Cmd + Shift + Z | Undo / Redo | Universal, but critical. Undo AI-generated changes you don't want. |
Open any Python file in VS Code. Use Cmd + P to open another file. Use Cmd + Shift + F to search for "def." Use Cmd + ` to open the terminal. Use Ctrl + G to jump to line 1. Do this 3 times without touching the mouse.
Installing Packages
pip installs packages—code other people wrote that you can use. Example: pip install requests installs a library for making web requests. You'll use this in Chapter 11.
Claude Code requires Node.js in addition to Python. Install it now to avoid a second setup session: go to nodejs.org and download the LTS version. Verify: node --version.
You just installed Node.js. In Phase 5, you'll use it to run Claude Code — an AI assistant that lives in your terminal. Here's what a Claude Code session looks like:
$ claude
╭──────────────────────────────────────╮
│ Claude Code │
│ │
│ /home/you/taskforge │
╰──────────────────────────────────────╯
> Explain the architecture of this project in one paragraph.
This project is a command-line task manager built in Python...
You're not ready to use this yet — you need to understand what code is and how to read it first. That's what the next 15 chapters are for. But when you get to Phase 5, setup will be one command: npm install -g @anthropic-ai/claude-code.
Micro-Exercise 1
Open your terminal. Type pwd (Mac/Linux) or cd (Windows) to see your current directory. Navigate to your Desktop: cd ~/Desktop.
Micro-Exercise 2
Verification: If 42 printed, everything works. You just created a folder, wrote a Python file into it, and ran it.
Create me.py that prints your name, the year, and why you're learning programming (3 separate print statements). Run: python3 me.py.
Verification: If all three lines appear in the terminal, your environment works.
If this doesn't work: (1) python3: command not found → Python isn't installed or not in PATH. On Windows, try python without the 3. On Mac, run brew install python3. (2) SyntaxError → check for missing quotes or parentheses. (3) File not found → make sure you're in the same directory as the file (ls to check).
TaskForge Connection
You now have everything needed to run TaskForge v0.1. After this chapter, the command python3 taskforge.py will work on your machine. You'll do exactly that in Chapter 04.
Interactive Exercises
Environment Setup Complete
Knowledge Check
What does source venv/bin/activate do?
Chapter 04 Reading Code Before Writing It
In the age of AI coding tools, you will read far more code than you write. When Claude Code generates 200 lines, your job is to evaluate them—not type them. This chapter teaches the skill that makes you a competent AI supervisor rather than a passive accepter.
Here's the paradigm shift: traditional education starts with writing code. AI-assisted work starts with reading code. When Claude Code generates 200 lines of Python for you, you won't write those lines—you'll read, evaluate, and decide whether to accept them. Reading code is your primary skill.
How to Read Code
Don't start at line 1 and grind forward. Use this three-pass approach:
Structure Pass
Scan for function definitions (def), classes, imports. What are the building blocks?
Logic Pass
Pick one function. Trace the data: what goes in, what comes out, what changes along the way?
Edge Pass
What happens with empty inputs? Huge inputs? Invalid data? This is where bugs hide—and where AI code most often fails.
Pattern Recognition
The table below shows patterns you haven't formally learned yet—functions, loops, conditionals, lists, and dictionaries all get their own chapters in Phase 2. That's intentional. Right now the goal is recognition, not writing. You should be able to look at a line like for item in list: and say "that's a loop—it repeats something." You don't need to write one from scratch yet. Think of it like reading a foreign language menu: you can recognize that pollo means chicken without knowing how to conjugate Spanish verbs.
You don't need to write code from memory. You need to recognize patterns when you see them:
| Pattern | What It Looks Like | What It Does |
|---|---|---|
| Function | def name(params): | A reusable block of logic |
| Loop | for item in list: | Repeats for each item |
| Conditional | if condition: | Chooses a path |
| Import | import json | Loads external code |
| Entry point | if __name__ == "__main__": | Runs when file is executed directly |
Before/After: Weak vs. Strong Reading
add_task creates a dict with id, description, and 'pending' status. complete_task iterates the list to find a matching id and updates the status. The main function runs an input loop with 4 commands. Edge case: if you enter a non-integer for task ID in done, it crashes with ValueError because there's no try/except."Micro-Exercise 1
What does this function do? What does double(5) return? What does double('hi') return?
def double(x):
return x * 2
Answers: It multiplies the input by 2. double(5) returns 10. double('hi') returns 'hihi'—because * on a string repeats it. The machine is literal.
Micro-Exercise 2
for item in ['a', 'b', 'c']:
print(item.upper())
How many times does the print run? What's the output?
Answer: 3 times. Output: A, B, C (each on a new line). The loop processes each item and .upper() converts to uppercase.
TaskForge v0.1 — The Code
Here's the complete source code for TaskForge v0.1. This is the spine project you'll build on for the rest of the course. Read it now using the three-pass approach.
# taskforge.py — v0.1
# A minimal command-line task manager
tasks = []
def add_task(description):
task = {"id": len(tasks) + 1, "description": description, "status": "pending"}
tasks.append(task)
return task
def complete_task(task_id):
for task in tasks:
if task["id"] == task_id:
task["status"] = "complete"
return task
return None
def list_tasks():
return tasks
def main():
while True:
command = input("\nTaskForge> ").strip().lower()
if command == "add":
desc = input("Description: ")
task = add_task(desc)
print(f"Added: #{task['id']} — {task['description']}")
elif command == "done":
task_id = int(input("Task ID: "))
result = complete_task(task_id)
if result:
print(f"Completed: #{result['id']}")
else:
print("Task not found.")
elif command == "list":
for t in list_tasks():
status = "✓" if t["status"] == "complete" else " "
print(f" [{status}] #{t['id']} — {t['description']}")
elif command == "quit":
break
else:
print("Commands: add, done, list, quit")
if __name__ == "__main__":
main()
while True:You'll notice while True: creates an infinite loop that only stops when the user types "quit" (which triggers break). You'll learn about while loops formally in Chapter 5, but the pattern is simple: keep repeating this block forever until something causes a break. For now, just recognize the shape—while True: at the top, break somewhere inside.
Run TaskForge Yourself
Up until now, you've been reading code and predicting output. This is the moment you run a real program. Follow these steps exactly.
Create the File
Open your terminal and create a new file called taskforge.py:
Open taskforge.py in your editor (VS Code: code taskforge.py) and paste the entire TaskForge v0.1 source code shown above.
Run It
You should see the TaskForge> prompt waiting for input.
Add a Task
TaskForge> add
Description: Buy groceries
Added: #1 — Buy groceriesList Tasks
TaskForge> list
[ ] #1 — Buy groceriesMark a Task Done
TaskForge> done
Task ID: 1
Completed: #1Verify It Worked
TaskForge> list
[✓] #1 — Buy groceries
TaskForge> quit
The checkmark confirms the status changed from "pending" to "complete." Type quit to exit.
python3: command not found — Python isn't installed. Return to the Installing Python section in Chapter 03. On Windows, try python instead of python3.
SyntaxError — Something went wrong when pasting. Make sure the indentation is consistent (all spaces, no tabs mixed in). Re-copy the code carefully.
FileNotFoundError — You're not in the same directory as taskforge.py. Run ls to check, then cd to the right folder.
A Worked Three-Pass Reading
Before you analyze TaskForge on your own, here's the three-pass method applied to a short function. Watch how each pass reveals a different layer of understanding.
def find_max(numbers):
if len(numbers) == 0:
return None
biggest = numbers[0]
for num in numbers:
if num > biggest:
biggest = num
return biggest
Structure Pass
One function called find_max. Takes one parameter: numbers. Has a loop inside. Returns something. 8 lines total.
Logic Pass
If the list is empty, return None. Otherwise, start by assuming the first element is the biggest. Walk through every number—if any number is bigger than the current biggest, update biggest. After checking all numbers, return the biggest one found.
Edge Pass
Empty list: returns None (handled explicitly). Single-element list: works fine—the loop runs once, biggest stays as the only element. All same values: works—num > biggest is never True, so the first value is returned. Negative numbers: works—nothing assumes positive values. Non-numeric input (e.g., strings): would crash on > comparison if types are mixed. No validation on input type.
Three passes, maybe 60 seconds total, and you understand the function completely. Apply this same method to TaskForge below.
"Indeed, the ratio of time spent reading versus writing is well over 10 to 1. We are constantly reading old code as part of the effort to write new code."
—Robert C. Martin, Clean Code
Read the TaskForge v0.1 code above. Write a code analysis answering these four questions:
- What does this program do?
- What data structure stores the tasks?
- What happens if you enter
doneand typeabcinstead of a number? - What happens if the list is empty and you type
list?
Verification: Your analysis should identify: a command-line task manager, a list of dictionaries, a crash on non-integer input (ValueError), and an empty output for an empty list. If you got 3 of 4, you pass.
If this doesn't work: If the code looks completely alien, return to Chapter 02 and re-read the sections on variables and functions. The patterns in TaskForge are the same patterns from Chapter 02 at larger scale.
Interactive Exercises
Fix the Bugs
This function is supposed to count how many words in a list are longer than a given length. It has 3 bugs. Find and fix all of them.
What should count start at — 0 or 1?
count + 1 calculates but doesn't save the result. How do you update a variable?
Check the variable name on the return line — is it the same as what you defined?
Knowledge Check
In TaskForge v0.1, what data structure stores the list of tasks?
Phase 1 Gate Checkpoint & TaskForge v0.1
Minimum Competency
Read a 30-line Python function, explain what it does, identify inputs/outputs, and spot one edge case.
Your Artifact
Your written TaskForge v0.1 analysis from Chapter 04's exercise. This IS your Phase 1 Gate proof.
Verification
Your analysis identifies at least 3 of 4 elements: purpose, data structure, crash case, empty case.
If you cannot predict the output of x = 5; x = x + 1; print(x) → return to Chapter 02.
TaskForge Checkpoint
You have read and analyzed TaskForge v0.1. You have NOT modified it. The project exists as a single .py file with no tests, no git, no structure. This is your baseline. In Phase 2, you'll start writing code to extend it.
What You Can Now Do
- Explain what a program is and how it executes
- Read variables, data types, functions, loops, and conditionals
- Set up and use a Python development environment
- Analyze a 40-line program and identify edge cases
You can read code. Now you need to write it. Why? Because when AI generates a function, you sometimes need to fix a bug, add a missing case, or write a test to verify it works. Phase 2 gives you writing fluency in Python—the language Claude Code operates in most often.