LESSON p.1 · Code · 180 min

Python from zero: expressions to testable functions

Python from zero: expressions to testable functions. Learn variables, types, branches, loops, functions, containers, and error messages and complete: Implement and test a pure-Pyth

Learning objectives

  1. Trace values, types, and control flow through a Python program.
  2. Extract repeated logic into functions with explicit inputs and returns.
  3. Read the final traceback line, then find the first relevant frame in your code.
  4. Write normal, boundary, and failure tests for a pure function.

Core concepts

Values, names, and types

A name refers to an object; it is not a permanently typed box. Inspect type and repr on tiny inputs before assuming which operations a string, number, list, or dictionary supports.

Branches and loops

Control flow determines which statement runs and how often. State initialization, update, and termination explicitly, then test empty, singleton, and repeated inputs.

Function contracts

A function needs explicit inputs, a return value, and a defined failure mode. Separate printing from returning so pure computation can be tested and later ported to NumPy or PyTorch.

Container choice

Lists preserve order, dictionaries support keyed lookup, sets remove duplicates, and tuples represent fixed records. Choose from the access pattern and complexity, not familiarity.

Tracebacks

Read the exception type and message at the bottom, then move upward to the first frame in your own file. Do not hide an unexplained error behind a broad try/except.

Build and verify

Implement and test a pure-Python text statistics tool

  • Write the expected tokens, word counts, and bigrams for a three-word input.
  • Implement tokenize and bigram_counts as single-purpose functions that return values.
  • Test empty, singleton, repeated, and bilingual text.
  • Trigger TypeError and KeyError deliberately and record the traceback lines that identify the fix.

Open the complete interactive lesson