AAmit’s LibraryLEARN · PRACTISE · REFLECT

Computers · Programming Atlas

Python Foundations

Core types, control flow, functions, collections, temporary toy files, JSON, expected errors, local modules and unittest. No package installation, external data, deployment or service integration.

Audience: Beginners who can save a text file and run an installed Python interpreter.

Practice: 4 to 6 hours, at your own pace.

Runtime and boundaries: This pack was tested with the installed CPython 3.9.6 on macOS 27.0.1. Python 3.9 is no longer supported upstream; this is a recorded offline learning environment, not a recommended deployment runtime. The cited 3.9 documentation currently describes 3.9.25, while the actual examples were tested on 3.9.6. No installation is needed or performed here. Save the example in a practice folder and run python3 followed by its quoted filename. Modules need the companion file beside the entry file. The browser Atlas exports text only and never runs Python.

Lessons

Run the installed interpreter deliberately

This pack was tested with the installed CPython 3.9.6 on macOS 27.0.1. Python 3.9 is no longer supported upstream; this is a recorded offline learning environment, not a recommended deployment runtime. The cited 3.9 documentation currently describes 3.9.25, while the actual examples were tested on 3.9.6. No installation is needed or performed here. Save the example in a practice folder and run python3 followed by its quoted filename. Modules need the companion file beside the entry file. The browser Atlas exports text only and never runs Python.

Values, names and explicit conversions

Python names refer to objects. This pack starts with int, float, bool, str and None, then collections. Use type or isinstance to investigate a value. The int constructor converts integer text and raises an error for invalid text. Use f-strings to format an output without changing the underlying value. A float is not an exact decimal arithmetic model; these examples use minutes and simple teaching values rather than financial calculations. Strings are immutable, so methods such as strip return a result you can assign or use.

Control flow follows indentation

Use if, elif and else for conditions. A for loop visits items in an iterable; enumerate adds a counter and range produces integers with an excluded stop value. A while loop needs a condition that can become false. Four spaces per indentation level make the examples easy to inspect. Keep state changes close to the condition they affect. Predict the first, last and empty-loop cases before running. Example 02 combines iteration, a conditional expression and a bounded countdown.

Functions make contracts visible

A function binds arguments to parameters and returns a result; without an explicit return value it returns None. Keep reusable calculations separate from printing or file access. State the accepted types, boundary values and errors. Avoid mutable default arguments in beginner helpers; create a fresh list inside a function when needed. Boolean is a subclass of integer, so a contract that excludes True and False needs an explicit check. Example 03 deliberately accepts whole-number minutes and tests invalid input.

Choose a collection for the relationship

Lists represent ordered mutable sequences, tuples fixed groupings, dictionaries key/value relationships and sets unique values. A comprehension can transform or filter a list, but a simple loop is often clearer when it also updates a dictionary. Use get with a default for counting. Sets have no promised display order; sort one before making deterministic output. A new list of references does not deep-copy the contained objects. The examples read records and build summaries without mutating the source records.

Keep file practice small and disposable

File paths have effects, so the toy examples create a new TemporaryDirectory inside the current writable practice folder. They use fixed filenames inside it, explicit UTF-8 encoding and context managers. They read only what they wrote, then let the context manager remove the temporary directory. A with block closes a file even when an exception interrupts the block. JSON is data, not code: serialize a tiny dictionary and decode only that bounded input. Never substitute a real document path into these exercises.

Errors should support recovery

Read the final exception type and message, then follow the traceback to the relevant call. Catch a specific expected exception where you can recover or add context; do not hide every error with a bare except. Validation can raise TypeError for the wrong kind of input and ValueError for a value outside the contract. A try/except/else structure distinguishes successful work from recovery. Keep the input that triggered a failure so a test can reproduce it. Examples 05 and Exercise B show deliberate recovery.

Modules and tests keep changes controlled

A module is a Python file. Save study_tools.py beside example 08 and import its named function. The main guard separates importing definitions from running the demonstration. Avoid naming your files json.py or unittest.py, which can hide the standard library modules in normal script execution. Use unittest to check normal, boundary and invalid cases. The included harness runs each authored example in a fresh temporary directory with a timeout and bytecode writing disabled; that is controlled testing of trusted examples, not a security sandbox for arbitrary code.

Reference cards

Types: int / float / bool / str / None

Whole numbers, floating-point values, truth values, text and absence of a value.

Flow: if / elif / else

Choose a block using a condition.

Flow: for / enumerate / range

Visit values, add counters and generate bounded integer sequences.

Flow: while

Repeat while a condition remains true; ensure progress toward stopping.

Functions: def / return

Define a reusable operation and give its result to the caller.

Collections: list / tuple

Ordered mutable sequence / fixed grouping.

Collections: dict.get(key, default)

Look up a key with an explicit fallback.

Collections: set / sorted

Deduplicate, then sort when stable output matters.

Errors: try / except / else

Handle a specific failure and separate the successful branch.

Errors: raise TypeError / ValueError

Signal a contract violation rather than silently producing a misleading result.

Files: with open(..., encoding="utf-8")

Close the handle reliably and make text encoding explicit.

Files: TemporaryDirectory(dir=".")

Create a disposable toy directory under the practice folder.

Data: json.dumps / json.loads

Encode and decode bounded JSON data.

Modules: from study_tools import total_minutes

Reuse a named function from a companion module.

Modules: if __name__ == "__main__"

Run the demonstration only when executed as the entry script.

Tests: unittest.TestCase / assertEqual / assertRaises

Check observable results and expected errors.

Examples and practice

Code below is reading material, not an execution console. Download the edition for the complete example files and companion modules.

Python 01 - Values and strings

Names refer to values. Division produces a float here, while a comparison produces a Boolean. The f-string formats display without changing the stored value. String methods return strings.

name = "Ada"
minutes = 45
sessions = 2
average = minutes / sessions
ready = sessions > 0
print(f"{name}: {minutes} minutes")
print(f"Average: {average:.1f}")
print(type(minutes).__name__, type(average).__name__, type(ready).__name__)
print("  Python  ".strip().upper())

Expected:

Ada: 45 minutes
Average: 22.5
int float bool
PYTHON
Python 02 - Branches and loops

Indentation defines blocks. enumerate gives each item a number. The while loop changes the value that controls termination. The stop value of range is excluded.

minutes = [5, 20, 10]
for index, value in enumerate(minutes, start=1):
    label = "long" if value >= 15 else "short"
    print(f"Session {index}: {label}")
countdown = 3
while countdown > 0:
    countdown -= 1
print(f"Countdown: {countdown}")
print(f"Range sum: {sum(range(1, 4))}")

Expected:

Session 1: short
Session 2: long
Session 3: short
Countdown: 0
Range sum: 6
Python 03 - Functions and contracts

This function accepts only integer minute counts, explicitly excluding Boolean values. It returns a result rather than printing internally. Errors define the input contract, and zero is the lower bound.

def remaining_minutes(limit, used):
    if any(type(value) is not int for value in (limit, used)):
        raise TypeError("Use whole-number minutes.")
    if limit < 0 or used < 0:
        raise ValueError("Minutes must be non-negative.")
    return max(0, limit - used)

print(f"Remaining: {remaining_minutes(60, 45)}")
print(f"Over budget: {remaining_minutes(10, 12)}")

Expected:

Remaining: 15
Over budget: 0
Python 04 - Collections and transformations

A list keeps an ordered sequence, dictionaries associate keys with values, a set deduplicates topics and a tuple holds a fixed pair. Sorting the set makes printed output deterministic. Filtering does not mutate the source list.

sessions = [{"topic": "HTML", "minutes": 20},
            {"topic": "Python", "minutes": 30},
            {"topic": "Python", "minutes": 15}]
long_sessions = [item["topic"] for item in sessions if item["minutes"] >= 20]
topics = sorted({item["topic"] for item in sessions})
totals = {}
for item in sessions:
    topic = item["topic"]
    totals[topic] = totals.get(topic, 0) + item["minutes"]
coordinate = (2, 3)
print(", ".join(long_sessions))
print(", ".join(topics))
print(f"Python total: {totals['Python']}")
print(f"Coordinate: {coordinate[0]}, {coordinate[1]}")

Expected:

HTML, Python
HTML, Python
Python total: 45
Coordinate: 2, 3
Python 05 - Handle expected errors

Catch the error you expect at the boundary where recovery makes sense. An unrelated programming error should remain visible. The parser accepts the integer text formats supported by int, including signs; it is not a strict digit-only validator.

def parse_minutes(text):
    if not isinstance(text, str):
        raise TypeError("Expected text.")
    value = int(text.strip())
    if value < 0:
        raise ValueError("Minutes cannot be negative.")
    return value

for raw in [" 15 ", "oops", "-2"]:
    try:
        print(f"Accepted: {parse_minutes(raw)}")
    except ValueError:
        print("Use a non-negative whole number.")

Expected:

Accepted: 15
Use a non-negative whole number.
Use a non-negative whole number.
Python 06 - Read and write a toy file

The file path is fixed inside a newly created toy directory, and both file handles close at the end of their with blocks. TemporaryDirectory then removes that directory. No existing document is read or overwritten. Run from a writable practice folder.

from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory(prefix="atlas-toy-", dir=".") as folder:
    path = Path(folder) / "notes.txt"
    with path.open("w", encoding="utf-8") as stream:
        stream.write("Read one example\nChange one value\n")
    with path.open("r", encoding="utf-8") as stream:
        lines = stream.read().splitlines()
    print(f"Line count: {len(lines)}")
    print(f"First: {lines[0]}")
print(f"Temporary folder removed: {not Path(folder).exists()}")

Expected:

Line count: 2
First: Read one example
Temporary folder removed: True
Python 07 - Round trip small JSON

JSON serializes a small data record. JSON false becomes Python False when decoded. This example handles only its own tiny string; it does not parse an external or unbounded input and does not execute JSON as code.

import json

record = {"topic": "Python", "minutes": 25, "done": False}
encoded = json.dumps(record, sort_keys=True)
decoded = json.loads(encoded)
print(encoded)
print(f"Same values: {decoded == record}")
print(f"Minutes: {decoded['minutes']}")

Expected:

{"done": false, "minutes": 25, "topic": "Python"}
Same values: True
Minutes: 25
Python 08 - Reuse a local module

Save both files in the same practice folder. The module provides a reusable function. The main guard runs the demonstration when the entry file is executed directly. Importing that entry file does not call main.

from study_tools import total_minutes

def main():
    print(f"Total: {total_minutes([10, 20, 5])}")

if __name__ == "__main__":
    main()

Expected:

Total: 35

Companion file: study_tools.py

def total_minutes(values):
    values = tuple(values)
    if any(type(value) is not int for value in values):
        raise TypeError("Use integers.")
    if any(value < 0 for value in values):
        raise ValueError("Use non-negative minutes.")
    return sum(values)
Python 09 - Test behavior with unittest

Tests compare observable behavior with a contract, including an invalid input. The suite uses a deterministic summary. A failing test changes the process exit code; proposed tests alone are not evidence that they ran.

import unittest

def square(value):
    if type(value) is not int:
        raise TypeError("Use an integer.")
    return value * value

class SquareTests(unittest.TestCase):
    def test_positive(self):
        self.assertEqual(square(3), 9)
    def test_zero(self):
        self.assertEqual(square(0), 0)
    def test_negative(self):
        self.assertEqual(square(-2), 4)
    def test_invalid(self):
        with self.assertRaises(TypeError):
            square("3")

suite = unittest.defaultTestLoader.loadTestsFromTestCase(SquareTests)
result = unittest.TestResult()
suite.run(result)
print(f"Tests: {result.testsRun}; failures: {len(result.failures)}; errors: {len(result.errors)}")
if not result.wasSuccessful():
    raise SystemExit(1)

Expected:

Tests: 4; failures: 0; errors: 0
Python Exercise A - Count study topics

The function keeps insertion order in the dictionary and returns an empty dictionary for no topics. It expects an iterable of strings; values of other types are outside this exercise contract.

def count_topics(topics):
    counts = {}
    for topic in topics:
        normalized = topic.strip().casefold()
        if normalized:
            counts[normalized] = counts.get(normalized, 0) + 1
    return counts

print(count_topics([" Python ", "HTML", "python", " "]))
print(count_topics([]))

Expected:

{'python': 2, 'html': 1}
{}

Practice: Count a list of topic strings without changing it. Ignore whitespace-only entries, normalize case and return a dictionary of counts. Test an empty list and repeated topics.

Python Exercise B - Recover from input errors

The exercise accepts a list of strings. Catching ValueError recovers from invalid integer text while leaving unrelated exceptions visible. Each item is accounted for as accepted or rejected.

def collect_minutes(values):
    accepted = []
    rejected = 0
    for raw in values:
        try:
            number = int(raw)
            if number < 0:
                raise ValueError("Negative minutes")
        except ValueError:
            rejected += 1
        else:
            accepted.append(number)
    return sum(accepted), rejected

total, rejected = collect_minutes(["10", "bad", "-1", "5"])
print(f"Total: {total}; rejected: {rejected}")

Expected:

Total: 15; rejected: 2

Practice: Given strings representing minutes, sum valid non-negative integers and count invalid entries. Return a pair. Do not stop at the first bad string; test empty input and all-invalid input.

Python Exercise C - A temporary JSON file

The temporary directory owns the file lifecycle. The code reads only the small record it just wrote, and cleanup is observable after leaving the context.

import json
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory(prefix="atlas-json-", dir=".") as folder:
    path = Path(folder) / "progress.json"
    progress = {"completed": ["types", "loops"], "next": "functions"}
    path.write_text(json.dumps(progress), encoding="utf-8")
    restored = json.loads(path.read_text(encoding="utf-8"))
    print(f"Completed: {len(restored['completed'])}")
    print(f"Next: {restored['next']}")
print(f"Cleaned up: {not Path(folder).exists()}")

Expected:

Completed: 2
Next: functions
Cleaned up: True

Practice: Write a tiny progress dictionary as UTF-8 JSON inside a new temporary directory, read it back, print a summary and show that the directory is removed. Never use an existing file path.

Prompt templates

These are editable planning prompts in the downloadable workbench; they do not contact an AI service here.

Build a small example
Create a minimal {language} example for: {goal}. Runtime: {runtime}. Constraints: {constraints}. Explain the structure, provide complete Python files, and give expected output plus standard-library tests and manual checks. Do not add libraries unless requested.
Debug a reproducible failure
Help debug this {language} case. Goal: {goal}. Runtime: {runtime}. Constraints: {constraints}. Ask for missing reproduction steps, exact error, expected result and actual result. Suggest the smallest evidence-based change and a regression check. Label guesses.
Design meaningful tests
Design tests for this {language} behavior: {goal}. Runtime: {runtime}. Constraints: {constraints}. Cover initial state, ordinary input, boundaries, invalid input, repeated actions and recovery. Give expected outputs. For file examples, use a fresh temporary directory and verify cleanup. Distinguish executed tests from proposed tests.
Refactor without changing behavior
Refactor this {language} implementation for: {goal}. Runtime: {runtime}. Constraints: {constraints}. State its observable contract, identify duplication, propose a small change, then show how existing tests establish preserved behavior. Do not change public inputs or outputs without flagging it.
Document the actual behavior
Document this {language} artifact: {goal}. Runtime: {runtime}. Constraints: {constraints}. Include purpose, setup, inputs, outputs, errors, one complete usage example, limitations and the real test evidence. Mark anything unverified and do not invent a compatibility claim.
Explain a concept with practice
Explain this {language} concept: {goal}. Runtime: {runtime}. Constraints: {constraints}. Use an original small example, predict its output, explain each meaningful step, then provide an exercise and a separate solution. Keep language features distinct from libraries and runtime APIs.

Further reading

Download the offline edition

Complete Atlas 0.11.0 ZIP (6,079,970 bytes) · 411-page guide and catalogue PDF · Versioned source JSON

Unzip the edition and open Programming and Scripting Atlas.html, Web Foundations.html, Python Foundations.html, SQL Foundations.html, Shell Foundations.html, TypeScript Foundations.html Data Formats Foundations.html, C Foundations.html C++ Foundations.html, Ruby Foundations.html, Perl Foundations.html, Swift Foundations.html, Makefile Foundations.html, awk Foundations.html, sed Foundations.html, jq Foundations.html, XSLT 1.0 Foundations.html, Tcl Foundations.html, Expect Foundations.html or Objective-C Foundations.html locally. The original interactive workbenches retain their offline prompt-building, local presets and export controls. Read the included README before running examples yourself. The workbench does not execute pasted code or call an AI service; prompt text is for you to inspect and use separately.

Version 0.11.0 is pinned here. The other 257 registry entries remain planned; this edition does not claim complete language coverage.

Evidence and limits

Objective-C adds 12 accepted native programs, four separate compiler or warning-policy rejections, 120 root checks and 147 independent native checks. Two rejection fixtures are warnings promoted by -Werror; they are not intrinsic syntax failures. No rejected fixture was executed. Tests dated 26 October 2026 used Apple Clang 21.0.0, ARC, C17 base mode, macOS SDK 27.0 headers and system Foundation 6.9 (5027.0.69) on macOS 27.0.1 arm64. This is introductory macOS/Foundation coverage, not iOS, GNUstep, Objective-C++, UI, concurrency or cross-platform coverage. No sanitizers, leak detector, race analysis, allocation/disk-full/permission fault injection or asynchronous timing tests were run. Trusted authored fixtures and process bounds do not establish an arbitrary-code sandbox.

The pinned Atlas 0.11.0 evidence records 607 browser checks, 55 Python harness checks plus four unittest methods, 74 SQL checks, 515 shell checks across 71 runs, 99 TypeScript checks, 51 Data Formats checks, 119 C checks, 116 C++ checks, 97 Ruby checks, 97 Perl checks, 105 Swift harness checks and 97 Makefile harness checks, 145 awk checks, 145 sed checks, 161 jq checks, 157 XSLT checks, 150 Tcl checks and 161 Expect checks. These are separate measures. Tcl and Expect tests are dated 26 October 2026 on installed Tcl 8.5.9 / Expect 5.45 with Tcl 8.5.9 on macOS arm64. These old versions are recorded teaching evidence, not deployment recommendations. Tcl has 12 accepted programs and Expect has 12 accepted controllers; each has four expected evaluation failures, not static compilation passes. Tcl has nine scenarios, five expected nonzero; Expect has seven scenarios, four expected nonzero. Expect default controllers invoke 15 toy children, including two expected child failures; one scenario also expects a failed child. Controller success does not mean every child succeeds. The authoring release records 100 owned-runner regression checks and 109 independent runner checks separately. Only authored fixtures and retained native child handles are covered. Cooperative cleanup requires event-loop progress; outer-timeout child cleanup remains uncertain without complete wait receipts. The retired PID-inspection branch was not retried. No sign-ins, secrets, network or external application control are taught or tested by this pack. awk and sed are text-processing languages; their examples use fixed authored ASCII input and the C locale with installed awk 20200816 and macOS sed on one platform. jq and XSLT each have 12 accepted examples and four separately rejected programs. jq has 21 scenarios, including five contract errors and one no-result status; XSLT has 20 scenarios, including five terminating messages and one CLI parameter rejection. Expected nonzero outcomes are not successful programs. Tests dated 26 October 2026 used jq 1.7.1-apple and XSLT 1.0 with libxslt 1.1.35/libxml2 2.9.13, fixed trusted programs and tiny authored inputs in the C locale on macOS arm64. These old installed XML libraries are recorded learning environments, not recommendations for untrusted-document processing. No imports, external documents, DTDs, custom/external entities, extension functions or generated source are covered. Command flags and bounds are not a complete sandbox. Standalone XPath remains planned; supporting XPath 1.0 expressions are limited to these XSLT examples. These tests do not establish GNU-tool equivalence, Unicode behavior, arbitrary-script safety or cross-platform portability. Swift has 12 accepted programs and four expected static rejections; Makefile has 12 accepted default targets, four expected parser rejections, eight additional scenarios and one expected recipe failure. Makefile is build scripting, not a general-purpose language. The Swift and Makefile test execution dates remain 25 October 2026. awk and sed tests are dated 26 October 2026. Delivery verification does not replace or refresh test execution dates. TypeScript includes 12 accepted programs executed as JavaScript and nine intentionally invalid cases correctly rejected. Each C/C++ pack has 12 accepted programs run normally and with AddressSanitizer/UndefinedBehaviorSanitizer, plus four expected compiler rejections that are never executed. Ruby and Perl each have 12 syntax-accepted programs executed and four expected syntax rejections; rejected cases are not successful programs. Syntax checks may execute compile-time code and are not arbitrary-code sandboxes. Sanitizer results cover executed paths only; leak detection and allocation-failure injection were not tested and memory safety is not proved.

Tested environments are Chrome 155, CPython 3.9.6, SQLite CLI 3.54.0, macOS sh/Bash 3.2.57/Zsh 5.9, TypeScript 6.0.3, Node 24.18.0 Apple Clang 21.0.0, Ruby 2.6.10p210 and Perl 5.34.1, Apple Swift 6.4 in Swift 6 mode and GNU Make 3.81 on one arm64 macOS host. C uses a C17 subset; C++ uses a C++20 subset with libc++ 220106. Python 3.9.6 is unsupported upstream. Ruby 2.6 is end-of-life upstream; the recorded installed interpreter is not a recommended modern runtime. Data Formats uses installed Tomli 1.0.3 through a private fallback; the Python tomllib branch was not run. No new-installation recommendation, complete language/format conformance, schema certification, hardened untrusted XML parsing or general-purpose execution sandbox is established. Other platforms, browsers and screen readers remain unverified. The 145 official references belong to the saved Atlas review, not fresh website-time verification.