Skip to main 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.

See The Python Work Loop

Python AI backbone capability chain

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

input -> data structure -> function -> file/API/output

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

Learning Order And Task List

Use this table as both the chapter guide and the task sheet.

PageFollow-along actionEvidence to keep
2.1.1 Python Introduction to 2.1.5 Flow ControlType small scripts with variables, input/output, conditions, and loops5 changed scripts with expected output
2.1.6 Data StructuresStore the same task list with a list, dict, and JSON-shaped objectA note explaining why one structure fits best
2.1.7 Function Basics and 2.1.8 Modules and PackagesSplit repeated logic into functions and a moduleA script with clear inputs and return values
2.2.2 Exception Handling and 2.2.3 File OperationsSave data, read it back, and handle a missing or broken fileA JSON/text file plus one debug note
2.2.1 OOP, 2.2.5 Iterators, and 2.2.6 Type HintsSkim first, then return when a project needs structure or clarityOne refactored function or class
2.3.1 Task Manager to 2.3.4 AI API ExperienceBuild small projects that save data, collect data, expose an API, and call an AI APIProject folders with README run commands
2.3.5 Follow-Along WorkshopCombine CLI commands, JSON persistence, stats, and report exportch02_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

First Runnable Loop

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:

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.

Depth Ladder

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.

Common Failures

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

Pass Check

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?

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.