Skip to content

2 Python Programming Fundamentals

Main visual for Python programming fundamentals

Chapter 2 has one job: help you turn a small idea into Python code that runs, saves data, handles errors, and can be explained.

Python AI backbone capability chain

Read the picture first. Most beginner Python programs are this loop:

inputdata structurefunctionfile/API/output

Python matters in AI because the same loop later becomes data cleaning, model training, RAG retrieval, API wrapping, and Agent tools.

Use this checklist as both the chapter guide and the task sheet. Move in order, and keep one reviewable artifact after each step.

  1. 2.1.1 Python Introduction to 2.1.5 Flow Control Follow along: type small scripts with variables, input/output, conditions, and loops. Evidence to keep: 5 changed scripts with expected output.

  2. 2.1.6 Data Structures Follow along: store the same task list with a list, dict, and JSON-shaped object. Evidence to keep: a note explaining why one structure fits best.

  3. 2.1.7 Function Basics and 2.1.8 Modules and Packages Follow along: split repeated logic into functions and a module. Evidence to keep: a script with clear inputs and return values.

  4. 2.2.2 Exception Handling and 2.2.3 File Operations Follow along: save data, read it back, and handle a missing or broken file. Evidence to keep: a JSON/text file plus one debug note.

  5. 2.2.1 OOP, 2.2.5 Iterators, and 2.2.6 Type Hints Follow along: skim first, then return when a project needs structure or clarity. Evidence to keep: one refactored function or class.

  6. 2.3.1 Task Manager to 2.3.4 AI API Experience Follow along: build small projects that save data, collect data, expose an API, and call an AI API. Evidence to keep: project folders with README run commands.

  7. 2.3.5 Follow-Along Workshop Follow along: combine CLI commands, JSON persistence, stats, and report export. Evidence to keep: ch02_output/ plus terminal output.

Key terms for this chapter:

TermMeaning
CLICommand-Line Interface: a program controlled by typed commands
I/OInput/Output: data entering a program and results leaving it
JSONA text format for nested data such as tasks and API responses
APIA doorway that lets one program call another program
SDKA library that wraps an API into easier functions

Run this in an empty practice folder. It creates a tiny JSON task manager without any third-party package.

import json
from pathlib import Path
DATA = Path("tasks.json")
def load_tasks():
if not DATA.exists():
return []
try:
return json.loads(DATA.read_text(encoding="utf-8"))
except json.JSONDecodeError:
return []
def save_tasks(tasks):
DATA.write_text(json.dumps(tasks, ensure_ascii=False, indent=2), encoding="utf-8")
tasks = load_tasks()
tasks.append({"title": "Learn Python file I/O", "done": False})
save_tasks(tasks)
print(f"saved {len(tasks)} task(s)")

Expected output:

Terminal window
saved 1 task(s)

Run it twice. The second run should print saved 2 task(s). That proves the program can save state and read it back.

  • The first run proves the program can create a data file.
  • The second run proves it can read previous state and append new data.
  • tasks.json is the real artifact; the printed line is only the quick confirmation.
  • If the count resets to 1, inspect the working directory and file path first.
LevelWhat you can prove
Minimum passYou can write expressions, conditions, loops, and functions that produce the expected output.
Project-readyThe program can persist data, handle one failure path, and explain its inputs and outputs in a README.
Deeper checkYou can separate core logic from file/API boundaries, add type hints where they clarify intent, and test one edge case before changing the code.

Keep this page’s proof of learning as a small evidence card:

Program Loop
input, processing, output, and saved state if any
Code File
Python file or notebook cell that can be rerun
Output
printed result, file result, or user-facing behavior
Failure Check
syntax, path, type, dependency, or control-flow issue
Expected Output
a rerunnable Python artifact that prepares for data and AI apps
SymptomFirst thing to checkUsual fix
Syntax errorThe reported line and the line above itCheck indentation, parentheses, quotes, and colons
File not foundThe current working directoryPrint Path.cwd() and move the file or change the path
JSON parsing failedWhether the file is empty or malformedAdd try/except and fall back to an empty list
Function is confusingInputs, return value, and hidden global stateSplit it into smaller functions with one responsibility
API call failsParameters, status code, and returned error bodyPrint the response safely and handle the error path

Move to Chapter 3 when you can answer these five questions:

  • What data enters the program, and what result leaves it?
  • When is a dictionary better than a list?
  • What folder is a file path relative to?
  • What is the difference between print and return?
  • Can another person run your project from the README?
Check reasoning and explanation
  1. Program input can be command-line text, user input, a file, or an API response. Output can be printed text, a returned value, a saved file, or a response sent to another program.
  2. A dictionary is better when each item needs named fields or fast lookup by key. A list is better for an ordered collection of similar items.
  3. Relative file paths are resolved from the current working directory, which may not be the script folder. Use Path.cwd() and Path(__file__).resolve() to check both.
  4. print() displays information for humans and returns None. return sends a value back to the caller so it can be reused, tested, or stored.
  5. A README is ready when a fresh terminal can install dependencies, run the command, and reproduce the expected output without hidden steps.

For a printable checklist, use 2.0 Study Guide and Task Sheet. The next chapter will use Python to process CSV files, analyze data, and connect databases.