THE BEGINNER PATH

Learn Python
by doing.

Write your first Python program in the browser, change it, and see its output. Each lesson gives you a worked example, a task you can check, and a next step.

177 lessons & projects Run real Python Quizzes & fixes
first_steps.pyPYTHON
1name = "Learner"2print(f"Hello, {name}!")3# Change it. Run it. Own it.
OUTPUTHello, Learner!
Small experiments make big progress.

THE WAY WE LEARN

One idea. Then try it yourself.

Each lesson follows the same simple rhythm, so you can focus on Python.

Understand

Get a short explanation and a concrete example. No walls of theory.

Run the code

Edit and execute Python in your browser. See what each change does.

Prove your progress

Pass the coding task and quiz to complete each lesson.

YOUR LEARNING PATH

Learn Python, step by step.

For a first session, try Hello, World!, then variables and types, then conditions. After that, follow the beginner path into small projects. Completed lessons stay saved in this browser. Search and filter all lessons →

0 / 177lessons completed
BEGINNER PATH

Beginner path

Build the foundations one step at a time.

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.

SMALL PROJECTS

Small projects

Put several skills together in a practical build.

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.

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 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 14030 min

Build a Python Survey Response Summarizer

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

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.

NEXT STEPS

Next steps

Go beyond the first Python concepts.

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.

MORE PROJECTS

More projects

Apply the next-step skills in two complete builds.

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

Deeper Python

Use Python's standard tools to solve more demanding tasks.

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.

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.

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.

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.

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 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 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.

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.

ADVANCED PROJECTS

Advanced projects

Combine several Python skills in a complete build.

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.

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.

ADVANCED PROJECT 12845 min

Build a Safe Text Command Menu

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

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.

PYTHON TOOLS AND FORMATS

Python tools and formats

Handle real-world text, bytes, files, identifiers, and measurements.

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.

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.

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 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 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 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.

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.

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 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 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.

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.

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.

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.

ALGORITHMS AND DATA STRUCTURES

Algorithms and data structures

Practice graphs, dynamic programming, and efficient data processing.

ALGORITHMS 10034 min

Schedule Dependent Tasks with Topological Sort

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

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 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.

KEEP LEARNING

Build a strong base. Then go further.

Work through projects and deeper Python topics, then use the lessons as a reference when questions come up.

Visit our YouTube channel