THE COURSE

Learn Python

New to coding? Begin with the first program, then learn values, decisions, repetition, and functions before a project. Use the goal-based paths below when you have something specific to build.

Run your first line of Python

First steps: print output · store values · make decisions. Or read Python History.

Choose what you want to build

Each route ends with a concrete result. Your completed lessons and next step are saved in this browser.

Start here · 10 steps

Build your first Python script

Print a result, accept input, make decisions, and finish a small program.

What you will make: A number-guessing game that reads guesses, gives feedback, and stops when the answer is found.

Progress is saved in this browser
Start: Hello, World!
View the 10 lessons and finish line
  1. Python History
  2. Hello, World!
  3. Variables and Types
  4. Basic Operators
  5. Input and Output
  6. Conditions
  7. Loops
  8. Functions
  9. Project: Tip CalculatorProject
  10. Project: Number Guessing GameProject
Finish line
  • Run a program that reads and prints a value.
  • Pass the conditions and loops coding tasks and quizzes.
  • Finish the number-guessing task and test a first-try win and a repeated guess.
Open the final coding task
After the basics · 15 steps

Organize and transform data

Work confidently with lists, dictionaries, sets, and efficient collection tools.

What you will make: A flashcard quiz that grades answers and lists the prompts to review.

Progress is saved in this browser
Start: Lists
View the 15 lessons and finish line
  1. Lists
  2. Dictionaries
  3. Tuples and Sets
  4. Slice Python Sequences Without Losing the Edges
  5. Shallow vs Deep Copy in Python
  6. List Comprehensions
  7. Dictionary and Set Comprehensions
  8. Loop with enumerate() and zip()
  9. Sort Python Lists and Dictionaries with key
  10. Count and Group Data with Counter and defaultdict
  11. Build Queues and Stacks with deque
  12. Schedule Jobs with heapq
  13. Find Insertion Points with bisect
  14. Project: Text AnalyzerProject
  15. Project: Flashcard QuizProject
Finish line
  • Build a collection from lists and dictionaries.
  • Pass a sorting or collection coding task and quiz.
  • Finish the flashcard project and check empty or mismatched responses.
Open the final coding task Run the companion project on GitHub
Practical data · 14 steps

Read, clean, and save real data

Handle text, files, CSV, JSON, dates, and web responses in practical projects.

What you will make: A log analyzer that counts severity levels, collects errors, and reports malformed rows.

Progress is saved in this browser
Start: String Formatting
View the 14 lessons and finish line
  1. String Formatting
  2. Basic String Operations
  3. Understand Unicode Text and UTF-8 Bytes
  4. Python Regular Expressions: search and findall
  5. Reading and Writing Files
  6. Work with File Paths using pathlib
  7. Read and Write JSON and CSV
  8. Manage Resources with Python with Statements
  9. Dates and Timedeltas in Python
  10. Convert Aware Datetimes with zoneinfo
  11. Calculate Money with Decimal
  12. Read a JSON API with urllib
  13. Project: CSV Expense TrackerProject
  14. Project: Analyze Application LogsProject
Finish line
  • Read and inspect local data with the file and pathlib lessons.
  • Parse structured text and test a malformed input.
  • Finish the log-analyzer project and check blank and broken rows.
Open the final coding task Run the companion project on GitHub
Debugging · 7 steps

Find and fix Python errors

Read tracebacks, validate inputs, log what happened, and test the repair.

What you will make: A reproducible bug report with a focused code fix and a test that catches the original failure.

Progress is saved in this browser
Start: Truthiness, None, and Identity in Python
View the 7 lessons and finish line
  1. Truthiness, None, and Identity in Python
  2. Exceptions
  3. Create a Custom Python Exception for Validation
  4. Read Python Tracebacks and Fix the Failing Layer
  5. Replace Debug Prints with Python Logging
  6. Test Python Functions with Assertions
  7. Test Dependencies with unittest.mock
Finish line
  • Reproduce an error and read its final traceback line.
  • Apply the smallest fix and verify an edge case.
  • Write a deterministic test using a fake dependency where needed.
Open the final coding task
Local Python · 5 steps

Run Python tools locally

Set up Python, import modules, accept arguments, and manage configuration.

What you will make: A local contact-book script plus a small command-line argument parser you can run from a terminal.

Progress is saved in this browser
Start: Installing Python and Virtual Environments
View the 5 lessons and finish line
  1. Installing Python and Virtual Environments
  2. Modules and Packages
  3. Read Environment Configuration Safely
  4. Build a Small CLI with argparse
  5. Project: Contact BookProject
Finish line
  • Set up a virtual environment and verify its Python interpreter.
  • Parse an option and handle invalid command-line input.
  • Finish the contact-book task and test a missing name.
Open the final coding task Run the companion project on GitHub
Next steps · 9 steps

Write reusable Python functions

Make functions easier to call, test, reuse, and reason about.

What you will make: A set of reusable functions with explicit arguments, type hints, and a checked caching or async example.

Progress is saved in this browser
Start: Function Arguments, Return Values, and Scope
View the 9 lessons and finish line
  1. Function Arguments, Return Values, and Scope
  2. Collect and Unpack Function Arguments
  3. Write Clearer Functions with Python Type Hints
  4. Iterators and Generators in Python
  5. Build Small Data Pipelines with itertools
  6. Understand Recursion and the Call Stack
  7. Memoize Pure Functions with lru_cache
  8. Write Python Decorators that Preserve Behavior
  9. Start Concurrent I/O with asyncio
Finish line
  • Write a function with a clear argument and return contract.
  • Pass an iterator, caching, or decorator coding task.
  • Finish the async practice task and explain what work can run concurrently.
Open the final coding task
Next steps · 6 steps

Model data with classes

Choose when to use objects, dataclasses, composition, and special methods.

What you will make: A small class with validated state and useful representations, comparison, or length behavior.

Progress is saved in this browser
Start: Classes and Objects
View the 6 lessons and finish line
  1. Classes and Objects
  2. Python dataclasses: Fields, Defaults, and asdict
  3. Choose Composition Over Unnecessary Inheritance
  4. Use Properties to Keep Python Objects Valid
  5. Make Objects Work with repr, ==, and len
  6. Read Structured Data with match and case
Finish line
  • Create a class or dataclass with named fields.
  • Validate an invalid assignment and test the resulting error.
  • Finish the special-methods task and inspect repr, equality, and length.
Open the final coding task
Build a data tool · 4 steps

Validate incoming data

Normalize text, inspect CSV and JSON Lines, and report the exact row that needs repair.

What you will make: A CSV import validator that returns accepted records and row-specific error messages.

Progress is saved in this browser
Start: Validate CSV Rows with DictReader
View the 4 lessons and finish line
  1. Validate CSV Rows with DictReader
  2. Process JSON Lines One Record at a Time
  3. Normalize Unicode Text for Search Keys
  4. Project: CSV Import Validator with Row ErrorsProject
Finish line
  • Inspect headers and missing CSV fields before using a row.
  • Keep text and line numbers traceable while validating input.
  • Finish the CSV import validator and test a blank cell and a malformed row.
Open the final coding task Run the companion project on GitHub
Build a business tool · 4 steps

Plan inventory orders

Use precise comparisons, clear summaries, and valid states to make a stock decision.

What you will make: A reorder planner that identifies shortfalls and prints a deterministic order list.

Progress is saved in this browser
Start: Compare Floating-Point Results with math.isclose
View the 4 lessons and finish line
  1. Compare Floating-Point Results with math.isclose
  2. See How Outliers Change Mean and Median
  3. Use Enums for Clear Python States
  4. Project: Inventory Reorder PlannerProject
Finish line
  • Choose tolerances and a summary that fit the data.
  • Represent allowed states explicitly and reject bad quantities.
  • Finish the inventory project and test an empty inventory and a boundary stock level.
Open the final coding task Run the companion project on GitHub
Build a scheduling tool · 4 steps

Detect booking conflicts

Model bookings with explicit constructors, preserve errors, and test interval boundaries.

What you will make: A booking conflict detector that reports overlapping time slots without false positives at touching boundaries.

Progress is saved in this browser
Start: Choose classmethod or staticmethod with a Parser
View the 4 lessons and finish line
  1. Choose classmethod or staticmethod with a Parser
  2. Explain Failures with Exception Chaining
  3. Test Cases with unittest Fixtures and subTest
  4. Project: Booking Conflict DetectorProject
Finish line
  • Create valid booking values before comparison.
  • Preserve the cause when converting a parsing error into a domain error.
  • Finish the conflict detector and test adjacent and overlapping bookings.
Open the final coding task Run the companion project on GitHub
Build a file tool · 4 steps

Verify a local archive

Read configuration, calculate content hashes, and inspect ZIP members safely.

What you will make: An archive manifest verifier that names missing, extra, and changed files.

Progress is saved in this browser
Start: Read INI Settings with configparser
View the 4 lessons and finish line
  1. Read INI Settings with configparser
  2. Check Content with hashlib
  3. Create ZIP Archives in Memory
  4. Project: Verify a ZIP Archive Against a ManifestProject
Finish line
  • Parse a setting with an explicit default and validation rule.
  • Hash bytes and inspect archive members without extracting them.
  • Finish the manifest verifier and test a modified member.
Open the final coding task Run the companion project on GitHub
Build a web concept tool · 4 steps

Explore an offline page graph

Parse links, control crawl state, and render discovered text safely using local fixture pages.

What you will make: An offline crawler that follows a bounded set of fixture links without revisiting pages.

Progress is saved in this browser
Start: Build Stateful Closures with nonlocal
View the 4 lessons and finish line
  1. Build Stateful Closures with nonlocal
  2. Build Query Strings with urllib.parse
  3. Escape Text for HTML Output
  4. Project: Offline Web Crawler on a Fixture GraphProject
Finish line
  • Separate URL paths and query parameters before comparing links.
  • Escape page text when rendering HTML and keep visited state explicit.
  • Finish the offline crawler and test a cycle and a page limit.
Open the final coding task Run the companion project on GitHub

All 177 lessons

The full catalog includes beginner concepts, standard-library tools, and projects. Filter by course stage when you want a sequence, or search for a function or task you need now.

177 results

LESSON 0011 min

Python History

Trace Python's beginnings, its name, and the arrival of Python 3.

LESSON 0110 min

Hello, World!

Run your first Python statements and recognize how Python displays output.

LESSON 0213 min

Variables and Types

Store values in variables and distinguish common Python data types.

LESSON 0315 min

Lists

Create a list, access its items, and change its contents.

LESSON 0413 min

Basic Operators

Use Python operators to calculate values and compare results.

LESSON 0512 min

String Formatting

Build readable text that includes variables and formatted numbers.

LESSON 0614 min

Basic String Operations

Read characters and slices from strings and apply common string methods.

LESSON 0715 min

Conditions

Use if, elif, and else in order: Python runs the first true branch and skips the rest. Compare values with ==, add colons, and indent each block.

LESSON 0816 min

Loops

Repeat work with for and while loops and recognize when a loop stops.

LESSON 0916 min

Functions

Define reusable code with parameters and return a result.

LESSON 1017 min

Classes and Objects

Create a simple class and give each instance its own data.

LESSON 1115 min

Dictionaries

Store related values by key and retrieve or update them.

LESSON 1215 min

Modules and Packages

Import a module and use a function from Python's standard library.

LESSON 1313 min

Input and Output

Understand text input, convert it when needed, and present useful output.

PRACTICE PROJECT 1419 min

Project: Tip Calculator

Combine functions, arithmetic, and formatted output to split a restaurant bill.

PRACTICE PROJECT 1520 min

Project: Number Guessing Game

Use comparisons, a function, and a loop to evaluate guesses until the answer is found.

PRACTICE PROJECT 1621 min

Project: Text Analyzer

Combine string methods, a loop, and a dictionary to summarize a sentence.

NEXT STEPS 1717 min

Tuples and Sets

Choose a tuple for a fixed group and a set for distinct values.

NEXT STEPS 1818 min

Exceptions

Catch expected runtime errors and return useful messages without hiding unrelated bugs.

NEXT STEPS 1919 min

Reading and Writing Files

Write and read a UTF-8 text file with a context manager.

NEXT STEPS 2020 min

Installing Python and Virtual Environments

Set up a local Python installation and understand how a virtual environment isolates project packages.

NEXT STEPS 2123 min

List Comprehensions

Build a new list from an iterable, add a filter, and explain the output before running it.

NEXT STEPS 2225 min

Function Arguments, Return Values, and Scope

Pass values into a function, return a result, and distinguish local names from names in the caller.

NEXT STEPS 2327 min

Read and Write JSON and CSV

Serialize and parse JSON, read CSV rows by header, and convert text fields deliberately.

NEXT STEPS 2424 min

Loop with enumerate() and zip()

Pair related values and number them without manually managing an index.

NEXT STEPS 2525 min

Dictionary and Set Comprehensions

Build key/value mappings and unique-value sets from iterable data with readable comprehensions.

NEXT STEPS 2627 min

Test Python Functions with Assertions

Write repeatable tests that compare actual results with expected results and cover boundaries.

NEXT STEPS 2725 min

Dates and Timedeltas in Python

Parse a calendar date, shift it by a number of days, and produce a predictable ISO date string.

PRACTICE PROJECT 2825 min

Project: CSV Expense Tracker

Read CSV rows in memory and calculate reliable expense totals by category.

PRACTICE PROJECT 2924 min

Project: Contact Book

Store, find, and update contacts with a dictionary and predictable name matching.

DEEPER PYTHON 3026 min

Sort Python Lists and Dictionaries with key

Use sorted(products, key=lambda item: item['price']) to return a new price-ordered list. Add reverse=True for descending order; equal-price items keep their input order.

DEEPER PYTHON 3127 min

Work with File Paths using pathlib

Build and inspect paths with pathlib, create missing parent folders, and read or write UTF-8 text safely.

DEEPER PYTHON 3228 min

Python Regular Expressions: search and findall

Use re.search() to get the first match or None, re.findall() to get all non-overlapping matches, and re.fullmatch() to validate an entire string.

DEEPER PYTHON 3328 min

Iterators and Generators in Python

Explain one-pass iteration and write a generator that yields values as they are requested.

DEEPER PYTHON 3428 min

Python dataclasses: Fields, Defaults, and asdict

Use @dataclass to generate an initializer, repr, and equality from annotated fields. Convert a record with asdict(), and use default_factory for each instance's list.

DEEPER PYTHON 3527 min

Count and Group Data with Counter and defaultdict

Count repeated values and group records without writing fragile missing-key checks.

DEEPER PYTHON 3627 min

Write Clearer Functions with Python Type Hints

Annotate function inputs and return values and explain what annotations do and do not enforce.

DEEPER PYTHON 3728 min

Write Python Decorators that Preserve Behavior

Wrap a callable to add behavior while forwarding its arguments and result, keeping metadata, and tracking state per decorated function.

DEEPER PYTHON 3829 min

Manage Resources with Python with Statements

Use with to bound resource lifetime and create a context manager that releases a file even when the body raises.

DEEPER PYTHON 3930 min

Build Small Data Pipelines with itertools

Compose iterator tools to stream data, bound consumption, compute running totals, and understand consecutive grouping.

DEEPER PYTHON 4030 min

Understand Recursion and the Call Stack

Trace recursive calls and write a function that stops correctly for empty and nested input.

DEEPER PYTHON 4129 min

Read Structured Data with match and case

Choose the first matching structural case and capture values from small event dictionaries.

DEEPER PYTHON 4230 min

Replace Debug Prints with Python Logging

Record messages at appropriate levels and filter them into a deterministic in-memory report.

DEEPER PYTHON 4332 min

Start Concurrent I/O with asyncio

Write a coroutine and use asyncio.gather to collect independent simulated I/O results in input order.

PRACTICE PROJECT 4428 min

Project: Analyze Application Logs

Turn multiline log text into severity counts, error messages, and a count of malformed rows.

PRACTICE PROJECT 4526 min

Project: Flashcard Quiz

Grade flashcard answers, report a score, and review missed questions without hiding a length mismatch.

DEEPER PYTHON 4627 min

Truthiness, None, and Identity in Python

Choose between a truth test, equality, and identity without treating valid zero values as missing.

DEEPER PYTHON 4729 min

Slice Python Sequences Without Losing the Edges

Predict and use sequence slices, including omitted bounds, negative indices, and a negative step.

DEEPER PYTHON 4830 min

Shallow vs Deep Copy in Python

Identify shared nested references and choose a copy depth that protects the original data.

DEEPER PYTHON 4929 min

Collect and Unpack Function Arguments

Distinguish variable positional arguments, named metadata, and a keyword-only option in one function.

DEEPER PYTHON 5029 min

Create a Custom Python Exception for Validation

Raise a meaningful exception type for invalid input while preserving the underlying conversion cause.

DEEPER PYTHON 5130 min

Read Python Tracebacks and Fix the Failing Layer

Use traceback frames and exception causes to locate a bug and add useful context at the correct layer.

DEEPER PYTHON 5230 min

Calculate Money with Decimal

Represent decimal money from text and round a final amount to cents with an explicit rule.

DEEPER PYTHON 5327 min

Build Queues and Stacks with deque

Choose FIFO or LIFO deliberately and serve queued items efficiently without changing the caller's list.

DEEPER PYTHON 5430 min

Schedule Jobs with heapq

Use heapq and an insertion counter to process lower numeric priorities first while preserving ties.

DEEPER PYTHON 5527 min

Find Insertion Points with bisect

Use bisect_left on a sorted sequence to locate an insertion point even when the value is absent.

DEEPER PYTHON 5630 min

Memoize Pure Functions with lru_cache

Use functools.lru_cache on a deterministic function and verify both results and cache reuse.

DEEPER PYTHON 5729 min

Understand Unicode Text and UTF-8 Bytes

Keep str and bytes distinct and perform an explicit UTF-8 round trip without changing the text.

DEEPER PYTHON 5831 min

Convert Aware Datetimes with zoneinfo

Convert an aware UTC instant to a named local zone and observe daylight saving changes.

DEEPER PYTHON 5931 min

Choose Composition Over Unnecessary Inheritance

Build a service around an injected sender object so its behavior can change without subclassing the service.

DEEPER PYTHON 6030 min

Use Properties to Keep Python Objects Valid

Protect an object's state with a property setter and compute a read-only derived value.

DEEPER PYTHON 6132 min

Read Environment Configuration Safely

Convert string-valued environment settings into a validated configuration with explicit defaults.

DEEPER PYTHON 6234 min

Read a JSON API with urllib

Decode a JSON response through an injected opener and validate its shape without requiring a live API.

DEEPER PYTHON 6332 min

Make Objects Work with repr, ==, and len

Implement three special methods with clear value semantics and handle unsupported comparisons correctly.

DEEPER PYTHON 6430 min

Test Dependencies with unittest.mock

Write a function with an injected dependency and test its return value and interaction without external I/O.

DEEPER PYTHON 6532 min

Build a Small CLI with argparse

Define a repeatable argument parser for a report command and validate its parsed options.

DEEPER PYTHON 6629 min

Compare Floating-Point Results with math.isclose

Use explicit numerical tolerances for approximate float results, including comparisons near zero.

DEEPER PYTHON 6731 min

Validate CSV Rows with DictReader

Read CSV by field name and validate its header, text, and numeric fields before using a row.

DEEPER PYTHON 6830 min

Process JSON Lines One Record at a Time

Distinguish one JSON document from line-delimited records and validate each decoded object.

DEEPER PYTHON 6928 min

See How Outliers Change Mean and Median

Calculate mean and median and explain why an extreme value affects them differently.

DEEPER PYTHON 7030 min

Normalize Unicode Text for Search Keys

Create a documented comparison key using Unicode NFC normalization and casefold.

DEEPER PYTHON 7127 min

Use Enums for Clear Python States

Represent a small workflow with Enum members and convert untrusted text at its boundary.

DEEPER PYTHON 7228 min

Build Stateful Closures with nonlocal

Return a closure that remembers state and use nonlocal only when rebinding that state.

DEEPER PYTHON 7330 min

Choose classmethod or staticmethod with a Parser

Use a classmethod for an alternative constructor and a staticmethod for class-related validation without instance state.

DEEPER PYTHON 7429 min

Explain Failures with Exception Chaining

Raise a domain-specific error from a lower-level exception without losing the original cause.

DEEPER PYTHON 7532 min

Test Cases with unittest Fixtures and subTest

Use setUp for fresh test data and subTest to label multiple inputs within a unittest method.

DEEPER PYTHON 7629 min

Build Query Strings with urllib.parse

Replace one URL query parameter without losing existing parameters or the fragment.

DEEPER PYTHON 7727 min

Escape Text for HTML Output

Render untrusted text as visible HTML text without treating its angle brackets as markup.

DEEPER PYTHON 7828 min

Check Content with hashlib

Calculate a deterministic SHA-256 checksum for text and detect when its content changes.

DEEPER PYTHON 7930 min

Read INI Settings with configparser

Parse a small INI configuration and return typed, validated job settings.

DEEPER PYTHON 8030 min

Create ZIP Archives in Memory

Create a ZIP archive from simple named text entries and inspect its contents without extraction.

ADVANCED PROJECT 8138 min

Project: Inventory Reorder Planner

Turn validated stock records into a stable, explainable reorder plan without changing the source records.

ADVANCED PROJECT 8237 min

Project: Booking Conflict Detector

Detect overlapping bookings with a half-open time rule and return conflict pairs in input order.

ADVANCED PROJECT 8340 min

Project: CSV Import Validator with Row Errors

Validate an entire CSV import and return accepted records alongside deterministic row-specific errors.

ADVANCED PROJECT 8442 min

Project: Verify a ZIP Archive Against a Manifest

Verify a small in-memory ZIP against an expected manifest without writing archive members to disk.

ADVANCED PROJECT 8543 min

Project: Offline Web Crawler on a Fixture Graph

Traverse an in-memory graph of HTML page fixtures in stable breadth-first order without network requests.

DEEPER PYTHON 8632 min

Query SQLite Safely with Parameters

Use SQLite placeholders for values and understand when a transaction commits or rolls back.

DEEPER PYTHON 8728 min

Generate Secure Random Tokens

Create unpredictable URL-safe tokens with an explicit minimum random-byte requirement.

DEEPER PYTHON 8828 min

Make Random Simulations Reproducible

Run a repeatable simulation with an independent random generator and validated trial count.

DEEPER PYTHON 8929 min

Layer Settings with ChainMap

Build a shallow configuration snapshot with explicit precedence across three mappings.

DEEPER PYTHON 9032 min

Replace a File Safely with a Temporary File

Replace a file only after a complete new value has been written to a temporary file.

DEEPER PYTHON 9131 min

Parse and Build Small XML Documents

Use ElementTree to parse trusted small XML and create escaped XML elements.

DEEPER PYTHON 9229 min

Compare Text with Unified Diffs

Create a unified diff for two text versions with stable labels and preserved line endings.

DEEPER PYTHON 9330 min

Calculate Exact Ratios with Fraction

Use Fraction for exact rational ratios and reject ambiguous float input.

PRACTICAL PYTHON 9428 min

Validate IP Addresses and Networks with ipaddress

Parse addresses and CIDR networks, then decide membership with ipaddress rather than text matching.

PRACTICAL PYTHON 9530 min

Copy and Move Files Safely with shutil

Copy a file without deleting its source, then move a file with explicit collision handling.

PRACTICAL PYTHON 9626 min

Configure Callbacks with functools.partial

Build a callable with selected arguments fixed while keeping other arguments open.

DEEPER PYTHON 9731 min

Define Structural Interfaces with typing.Protocol

Use a Protocol to describe interchangeable objects and understand what runtime checks do and do not prove.

DEEPER PYTHON 9829 min

Inspect Function Signatures and Validate Arguments

Use inspect.signature and bind to validate a proposed function call without running the function.

SAFE PYTHON 9930 min

Parse Python Literals Without eval

Use ast.literal_eval for literal syntax while enforcing an application-specific shape and size limit.

ALGORITHMS 10034 min

Schedule Dependent Tasks with Topological Sort

Return tasks in an order that places every prerequisite before its dependent task.

PRACTICAL PYTHON 10130 min

Build and Parse Email Messages Offline

Construct a plain-text EmailMessage and parse its bytes while keeping transport separate.

DEEPER PYTHON 10230 min

Encode Binary Data with Python base64

Convert text to bytes before Base64 encoding and validate decoded input before using it.

DEEPER PYTHON 10330 min

Authenticate Messages with Python hmac

Sign a byte message with HMAC-SHA256 and verify it using a shared secret key.

DEEPER PYTHON 10430 min

Create Stable and Random UUIDs in Python

Build a reproducible UUID from a namespace and normalized name, and distinguish it from a random UUID.

DEEPER PYTHON 10530 min

Compress Text and Bytes with Python gzip

Compress UTF-8 text into gzip bytes and recover the original text.

DEEPER PYTHON 10630 min

Pack Binary Records with Python struct

Pack an unsigned identifier and status byte into a stable three-byte record.

DEEPER PYTHON 10730 min

Test Text Streams with Python StringIO

Pass a StringIO stream into a function and rewind it before a second read.

DEEPER PYTHON 10830 min

Read TOML Configuration with Python tomllib

Load a TOML configuration string and validate a required positive integer setting.

DEEPER PYTHON 10930 min

Find Files with Python glob and fnmatch

Select matching file names from a known list using fnmatchcase and deterministic sorting.

DEEPER PYTHON 11030 min

Benchmark Tiny Python Functions with timeit

Compute a per-call benchmark from repeated timeit runs without claiming universal speed.

DEEPER PYTHON 11130 min

Find a Shortest Unweighted Path with BFS

Return a shortest path in an unweighted adjacency-list graph using a FIFO queue.

DEEPER PYTHON 11230 min

Detect Directed Graph Cycles with DFS

Detect whether a directed adjacency-list graph contains a cycle.

DEEPER PYTHON 11330 min

Solve Coin Change with Dynamic Programming

Return the minimum number of positive-denomination coins for a target amount, or None if unreachable.

DEEPER PYTHON 11430 min

Compute a Moving Average with a Sliding Window

Return every fixed-size moving average with one pass and a running sum.

DEEPER PYTHON 11530 min

Count Connected Components with Union-Find

Count connected components in an undirected graph using a disjoint-set structure.

DEEPER PYTHON 11630 min

Answer Range Sum Queries with Prefix Sums

Build prefix totals and compute sums for half-open index ranges.

DEEPER PYTHON 11729 min

Capture and Replace Text with Python Regex

Use named capture groups and a re.sub callback to transform complete order codes without changing unrelated text.

DEEPER PYTHON 11828 min

Validate Dataclasses with __post_init__

Reject reversed range bounds and calculate a derived span immediately after a generated dataclass initializer runs.

DEEPER PYTHON 11930 min

Manage Async Tasks with TaskGroup and Cancellation

Use asyncio.TaskGroup to wait for related tasks, retrieve results in input order, and understand sibling cancellation after failure.

DEEPER PYTHON 12030 min

Merge Dictionaries and Handle Duplicate Keys

Merge dictionaries while making duplicate-key behavior explicit and leaving inputs unchanged.

DEEPER PYTHON 12130 min

Compare Groups with Python Set Operations

Compare two groups with union, intersection, and difference while returning deterministic sorted results.

DEEPER PYTHON 12230 min

Read Nested JSON with Explicit Missing-Field Rules

Extract a city from nested JSON data while distinguishing a missing optional value from an invalid object shape.

DEEPER PYTHON 12330 min

Read and Write CSV with Quoting and Dialects

Read and write CSV records containing commas and quotation marks without splitting lines manually.

DEEPER PYTHON 12430 min

Serialize Datetime and Decimal Values to JSON

Serialize datetime and Decimal values to JSON with an explicit representation and reject unsupported types.

DEEPER PYTHON 12530 min

Project: Build a Gradebook Report

Build a small gradebook report from CSV data with validated scores, averages, and deterministic ranking.

DEEPER PYTHON 12630 min

Write Clear CLI Output and Exit Codes

Separate successful CLI output from error diagnostics and return meaningful exit codes.

DEEPER PYTHON 12730 min

Parse Quoted Command Input with shlex

Parse a small command line while preserving quoted arguments and rejecting malformed input.

ADVANCED PROJECT 12845 min

Build a Safe Text Command Menu

Parse and execute add, remove, and show commands against an in-memory inventory.

DEEPER PYTHON 12930 min

Dispatch Functions by Type with singledispatch

Register type-specific handlers and distinguish bool from int.

DEEPER PYTHON 13030 min

Cache Derived Values with cached_property

Cache an expensive derived value and invalidate it whenever its inputs change.

DEEPER PYTHON 13130 min

Build Stateful Callable Objects with __call__

Use __call__ to make a validated counter object invokable while it keeps its own state.

DEEPER PYTHON 13230 min

Test Binary Streams with io.BytesIO

Read a length-prefixed binary record from BytesIO and reject incomplete payloads.

DEEPER PYTHON 13330 min

Read Text Files with Explicit Encoding and Line Rules

Decode UTF-8 bytes and split lines consistently across LF, CRLF, and CR endings.

ADVANCED PROJECT 13445 min

Build an Offline Duplicate File Scanner

Group equal byte contents by path and explain how to extend the algorithm to real files.

DEEPER PYTHON 13530 min

Find Month Boundaries with calendar.monthrange

Return the first and last date of a month, including leap-year February.

DEEPER PYTHON 13630 min

Parse and Format Timestamps with datetime

Validate a fixed UTC timestamp format before producing an ISO-style output string.

DEEPER PYTHON 13730 min

Build a Python Habit Streak Analyzer

Find the longest run of consecutive calendar dates in a list of habit check-ins.

DEEPER PYTHON 13830 min

Calculate Quantiles and Percentiles with Python

Calculate and interpret inclusive quartiles for a numeric dataset with an explicit method.

DEEPER PYTHON 13930 min

Use Weighted Random Sampling in Python

Draw one outcome according to validated nonnegative weights using an injected random generator.

DEEPER PYTHON 14030 min

Build a Python Survey Response Summarizer

Normalize optional survey answers and compute sorted choice counts plus an optional rating average.

DEEPER PYTHON 14130 min

Understand Python Algorithmic Complexity with Measured Inputs

Measure how comparison counts grow for linear and binary search on increasing sorted inputs.

DEEPER PYTHON 14230 min

Solve Sorted-List Pair Sums with Two Pointers

Find a pair that reaches a target sum in a sorted list without testing every pair.

DEEPER PYTHON 14330 min

Find Combinations with Python Backtracking and Pruning

Generate unique positive-integer combinations that sum to a target while pruning impossible branches.

DEEPER PYTHON 14430 min

Validate JSON from HTTP Responses in Python

Validate an HTTP-like response's status, JSON syntax, and expected field types before using its data.

DEEPER PYTHON 14530 min

Retry Transient Failures with Timeouts and Backoff in Python

Retry only transient local failures with a bounded exponential delay schedule.

DEEPER PYTHON 14630 min

Build an Offline Python API Client Simulator

Build a deterministic offline client that retries temporary failures, validates user JSON, and caches only successful records.

PRACTICAL PYTHON 14725 min

Python TypedDict: Required and Optional Keys

Model a dictionary record with one required key and one optional key, then use it without assuming TypedDict validates values at runtime.

PRACTICAL PYTHON 14830 min

Pillow Resize Image Without Losing Aspect Ratio

Resize an image into a maximum width and height without distortion, upscaling, or changing the original image.

PRACTICAL PYTHON 14930 min

Pandas GroupBy Multiple Columns with Named Aggregations

Summarize sales by region and product, with separate total amount and distinct order count columns.

PRACTICAL PYTHON 15030 min

Pandas Merge on Multiple Columns Without Duplicate Matches

Join orders with regional prices using both SKU and region, rejecting duplicate lookup keys and null join keys.

PRACTICAL PYTHON 15130 min

Pandas Drop Duplicates by Column and Keep the Latest Row

Deduplicate records by email while retaining the latest timestamped row and leaving the input unchanged.

PYTHON TOOLS 15230 min

Python Create Temp File with NamedTemporaryFile

Create a UTF-8 temporary file, read it from the correct cursor position, and clean it up automatically.

PYTHON TOOLS 15330 min

Python Rotating File Handler: Limit Log File Size

Rotate a UTF-8 log file by byte size and retain a bounded number of backups.

PYTHON TOOLS 15430 min

Python argparse Subcommands with add_subparsers

Give add and list commands separate arguments and reject a missing or incomplete command.

PYTHON TOOLS 15530 min

Python concurrent.futures as_completed: Handle Results as They Finish

Consume futures in completion order, associate each result with its input, and handle individual failures.

PYTHON TOOLS 15630 min

Python subprocess.run Command: Capture Output Safely

Run a known local Python child process with separate arguments, capture output, and handle status and timeout.

PYTHON TOOLS 15728 min

Python zipfile extract: unpack selected files safely

Inspect ZIP members, allow only expected text files, and extract them into one chosen directory.

PYTHON TOOLS 15830 min

FastAPI request body: validate JSON with a Pydantic model

Declare a POST request body, separate it from path parameters, and understand automatic 422 validation responses.

PYTHON TOOLS 15928 min

BeautifulSoup parse table: extract HTML rows into Python records

Select one HTML table, read its header and cells, and turn rows into records without confusing nested tables.

PYTHON TOOLS 16028 min

Python cProfile example: find slow functions and read pstats

Profile a function, sort cumulative time, and distinguish call counts from elapsed time.

PYTHON TOOLS 16128 min

openpyxl read Excel in Python: rows, headers, and values

Read an .xlsx workbook with openpyxl and turn a sheet with headers into validated records.

PRACTICAL PYTHON 16228 min

NumPy reshape: change array dimensions without shape errors

Reshape a one-dimensional NumPy array into a chosen number of columns, with a clear check for incompatible sizes.

PRACTICAL PYTHON 16330 min

Pandas pivot table with multiple aggregations

Build a region-by-product pivot table with both sum and mean of an amount column, then read each measure reliably.

PRACTICAL PYTHON 16428 min

Pandas fillna: different values for different columns

Fill missing city and score values with separate defaults while leaving other columns and the input DataFrame unchanged.

DEEPER PYTHON 16530 min

asyncio.gather: run tasks together and handle errors

Run independent coroutines together and turn returned exceptions into clear per-item results without losing input order.

PRACTICAL PYTHON 16630 min

pytest.mark.parametrize: test many cases with one function

Design a small table of input-output cases and run it as separate named pytest cases in a local project.

PRACTICAL PYTHON 16727 min

Pandas to_datetime: Parse Dates and Find Invalid Rows

Convert date strings to UTC timestamps while identifying invalid or missing source values.

PRACTICAL PYTHON 16826 min

Matplotlib savefig: Export a PNG Without Clipped Labels

Save the exact Figure you created to a PNG file at 200 DPI with labels inside the output.

PRACTICAL PYTHON 16925 min

Python re.findall: Return Full Matches Instead of Groups

Extract complete ERR- and WARN- codes without returning only captured prefixes or partial codes.

PRACTICAL PYTHON 17029 min

Pydantic field_validator: Normalize and Validate a Field

Normalize a handle before type validation while rejecting blank or non-string input.

PRACTICAL PYTHON 17128 min

FastAPI Query Parameters: Validate skip and limit

Add typed, bounded skip and limit query parameters to a GET route and apply them to a collection.

PYTHON TOOLS 17228 min

pytest tmp_path: test file-writing code without touching real files

Use pytest's tmp_path fixture to test a file writer in an isolated directory and assert the saved content.

DEEPER PYTHON 17328 min

Dataclass to dict in Python: asdict, nested objects, and copy behavior

Convert dataclass instances to dictionaries with asdict and understand nested conversion versus shallow field access.

PYTHON TOOLS 17430 min

jsonschema validate Python data: required fields and readable errors

Validate Python data against a JSON Schema, collect errors, and distinguish a bad instance from a bad schema.

PYTHON TOOLS 17528 min

Python CSV to JSON: convert rows with DictReader and json.dumps

Turn CSV rows into JSON objects with headers, UTF-8 text, and explicit handling for malformed rows.

PYTHON TOOLS 17628 min

NumPy boolean indexing: filter arrays with masks and avoid copy surprises

Build a Boolean mask, select matching NumPy values or rows, and distinguish a selected copy from assignment into the source.