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.
Prefer the story first? Read lesson 00: Python History.
name = "Learner"2print(f"Hello, {name}!")3# Change it. Run it. Own it.CHOOSE YOUR ROUTE
Start a course or repair a bug.
Pick the route that matches what brought you here today.
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 →
Beginner path
Build the foundations one step at a time.
Python History
Trace Python's beginnings, its name, and the arrival of Python 3.
Hello, World!
Run your first Python statements and recognize how Python displays output.
Variables and Types
Store values in variables and distinguish common Python data types.
Lists
Create a list, access its items, and change its contents.
Basic Operators
Use Python operators to calculate values and compare results.
String Formatting
Build readable text that includes variables and formatted numbers.
Basic String Operations
Read characters and slices from strings and apply common string methods.
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.
Loops
Repeat work with for and while loops and recognize when a loop stops.
Functions
Define reusable code with parameters and return a result.
Classes and Objects
Create a simple class and give each instance its own data.
Dictionaries
Store related values by key and retrieve or update them.
Modules and Packages
Import a module and use a function from Python's standard library.
Input and Output
Understand text input, convert it when needed, and present useful output.
Small projects
Put several skills together in a practical build.
Project: Tip Calculator
Combine functions, arithmetic, and formatted output to split a restaurant bill.
Project: Number Guessing Game
Use comparisons, a function, and a loop to evaluate guesses until the answer is found.
Project: Text Analyzer
Combine string methods, a loop, and a dictionary to summarize a sentence.
Project: Build a Gradebook Report
Build a small gradebook report from CSV data with validated scores, averages, and deterministic ranking.
Build a Python Habit Streak Analyzer
Find the longest run of consecutive calendar dates in a list of habit check-ins.
Build a Python Survey Response Summarizer
Normalize optional survey answers and compute sorted choice counts plus an optional rating average.
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
Go beyond the first Python concepts.
Tuples and Sets
Choose a tuple for a fixed group and a set for distinct values.
Exceptions
Catch expected runtime errors and return useful messages without hiding unrelated bugs.
Reading and Writing Files
Write and read a UTF-8 text file with a context manager.
Installing Python and Virtual Environments
Set up a local Python installation and understand how a virtual environment isolates project packages.
List Comprehensions
Build a new list from an iterable, add a filter, and explain the output before running it.
Function Arguments, Return Values, and Scope
Pass values into a function, return a result, and distinguish local names from names in the caller.
Read and Write JSON and CSV
Serialize and parse JSON, read CSV rows by header, and convert text fields deliberately.
Loop with enumerate() and zip()
Pair related values and number them without manually managing an index.
Dictionary and Set Comprehensions
Build key/value mappings and unique-value sets from iterable data with readable comprehensions.
Test Python Functions with Assertions
Write repeatable tests that compare actual results with expected results and cover boundaries.
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
Apply the next-step skills in two complete builds.
Project: CSV Expense Tracker
Read CSV rows in memory and calculate reliable expense totals by category.
Project: Contact Book
Store, find, and update contacts with a dictionary and predictable name matching.
Deeper Python
Use Python's standard tools to solve more demanding tasks.
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.
Work with File Paths using pathlib
Build and inspect paths with pathlib, create missing parent folders, and read or write UTF-8 text safely.
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.
Iterators and Generators in Python
Explain one-pass iteration and write a generator that yields values as they are requested.
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.
Count and Group Data with Counter and defaultdict
Count repeated values and group records without writing fragile missing-key checks.
Write Clearer Functions with Python Type Hints
Annotate function inputs and return values and explain what annotations do and do not enforce.
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.
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.
Build Small Data Pipelines with itertools
Compose iterator tools to stream data, bound consumption, compute running totals, and understand consecutive grouping.
Understand Recursion and the Call Stack
Trace recursive calls and write a function that stops correctly for empty and nested input.
Read Structured Data with match and case
Choose the first matching structural case and capture values from small event dictionaries.
Replace Debug Prints with Python Logging
Record messages at appropriate levels and filter them into a deterministic in-memory report.
Start Concurrent I/O with asyncio
Write a coroutine and use asyncio.gather to collect independent simulated I/O results in input order.
Truthiness, None, and Identity in Python
Choose between a truth test, equality, and identity without treating valid zero values as missing.
Slice Python Sequences Without Losing the Edges
Predict and use sequence slices, including omitted bounds, negative indices, and a negative step.
Shallow vs Deep Copy in Python
Identify shared nested references and choose a copy depth that protects the original data.
Collect and Unpack Function Arguments
Distinguish variable positional arguments, named metadata, and a keyword-only option in one function.
Create a Custom Python Exception for Validation
Raise a meaningful exception type for invalid input while preserving the underlying conversion cause.
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.
Calculate Money with Decimal
Represent decimal money from text and round a final amount to cents with an explicit rule.
Build Queues and Stacks with deque
Choose FIFO or LIFO deliberately and serve queued items efficiently without changing the caller's list.
Schedule Jobs with heapq
Use heapq and an insertion counter to process lower numeric priorities first while preserving ties.
Find Insertion Points with bisect
Use bisect_left on a sorted sequence to locate an insertion point even when the value is absent.
Memoize Pure Functions with lru_cache
Use functools.lru_cache on a deterministic function and verify both results and cache reuse.
Understand Unicode Text and UTF-8 Bytes
Keep str and bytes distinct and perform an explicit UTF-8 round trip without changing the text.
Convert Aware Datetimes with zoneinfo
Convert an aware UTC instant to a named local zone and observe daylight saving changes.
Choose Composition Over Unnecessary Inheritance
Build a service around an injected sender object so its behavior can change without subclassing the service.
Use Properties to Keep Python Objects Valid
Protect an object's state with a property setter and compute a read-only derived value.
Read Environment Configuration Safely
Convert string-valued environment settings into a validated configuration with explicit defaults.
Read a JSON API with urllib
Decode a JSON response through an injected opener and validate its shape without requiring a live API.
Make Objects Work with repr, ==, and len
Implement three special methods with clear value semantics and handle unsupported comparisons correctly.
Test Dependencies with unittest.mock
Write a function with an injected dependency and test its return value and interaction without external I/O.
Build a Small CLI with argparse
Define a repeatable argument parser for a report command and validate its parsed options.
Compare Floating-Point Results with math.isclose
Use explicit numerical tolerances for approximate float results, including comparisons near zero.
Validate CSV Rows with DictReader
Read CSV by field name and validate its header, text, and numeric fields before using a row.
Process JSON Lines One Record at a Time
Distinguish one JSON document from line-delimited records and validate each decoded object.
See How Outliers Change Mean and Median
Calculate mean and median and explain why an extreme value affects them differently.
Normalize Unicode Text for Search Keys
Create a documented comparison key using Unicode NFC normalization and casefold.
Use Enums for Clear Python States
Represent a small workflow with Enum members and convert untrusted text at its boundary.
Build Stateful Closures with nonlocal
Return a closure that remembers state and use nonlocal only when rebinding that state.
Choose classmethod or staticmethod with a Parser
Use a classmethod for an alternative constructor and a staticmethod for class-related validation without instance state.
Explain Failures with Exception Chaining
Raise a domain-specific error from a lower-level exception without losing the original cause.
Test Cases with unittest Fixtures and subTest
Use setUp for fresh test data and subTest to label multiple inputs within a unittest method.
Build Query Strings with urllib.parse
Replace one URL query parameter without losing existing parameters or the fragment.
Escape Text for HTML Output
Render untrusted text as visible HTML text without treating its angle brackets as markup.
Check Content with hashlib
Calculate a deterministic SHA-256 checksum for text and detect when its content changes.
Read INI Settings with configparser
Parse a small INI configuration and return typed, validated job settings.
Create ZIP Archives in Memory
Create a ZIP archive from simple named text entries and inspect its contents without extraction.
Query SQLite Safely with Parameters
Use SQLite placeholders for values and understand when a transaction commits or rolls back.
Generate Secure Random Tokens
Create unpredictable URL-safe tokens with an explicit minimum random-byte requirement.
Make Random Simulations Reproducible
Run a repeatable simulation with an independent random generator and validated trial count.
Layer Settings with ChainMap
Build a shallow configuration snapshot with explicit precedence across three mappings.
Replace a File Safely with a Temporary File
Replace a file only after a complete new value has been written to a temporary file.
Parse and Build Small XML Documents
Use ElementTree to parse trusted small XML and create escaped XML elements.
Compare Text with Unified Diffs
Create a unified diff for two text versions with stable labels and preserved line endings.
Calculate Exact Ratios with Fraction
Use Fraction for exact rational ratios and reject ambiguous float input.
Define Structural Interfaces with typing.Protocol
Use a Protocol to describe interchangeable objects and understand what runtime checks do and do not prove.
Inspect Function Signatures and Validate Arguments
Use inspect.signature and bind to validate a proposed function call without running the function.
Validate Dataclasses with __post_init__
Reject reversed range bounds and calculate a derived span immediately after a generated dataclass initializer runs.
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.
Merge Dictionaries and Handle Duplicate Keys
Merge dictionaries while making duplicate-key behavior explicit and leaving inputs unchanged.
Compare Groups with Python Set Operations
Compare two groups with union, intersection, and difference while returning deterministic sorted results.
Dispatch Functions by Type with singledispatch
Register type-specific handlers and distinguish bool from int.
Cache Derived Values with cached_property
Cache an expensive derived value and invalidate it whenever its inputs change.
Build Stateful Callable Objects with __call__
Use __call__ to make a validated counter object invokable while it keeps its own state.
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.
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
Combine several Python skills in a complete build.
Project: Analyze Application Logs
Turn multiline log text into severity counts, error messages, and a count of malformed rows.
Project: Flashcard Quiz
Grade flashcard answers, report a score, and review missed questions without hiding a length mismatch.
Project: Inventory Reorder Planner
Turn validated stock records into a stable, explainable reorder plan without changing the source records.
Project: Booking Conflict Detector
Detect overlapping bookings with a half-open time rule and return conflict pairs in input order.
Project: CSV Import Validator with Row Errors
Validate an entire CSV import and return accepted records alongside deterministic row-specific errors.
Project: Verify a ZIP Archive Against a Manifest
Verify a small in-memory ZIP against an expected manifest without writing archive members to disk.
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.
Build a Safe Text Command Menu
Parse and execute add, remove, and show commands against an in-memory inventory.
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
Handle real-world text, bytes, files, identifiers, and measurements.
Validate IP Addresses and Networks with ipaddress
Parse addresses and CIDR networks, then decide membership with ipaddress rather than text matching.
Copy and Move Files Safely with shutil
Copy a file without deleting its source, then move a file with explicit collision handling.
Configure Callbacks with functools.partial
Build a callable with selected arguments fixed while keeping other arguments open.
Parse Python Literals Without eval
Use ast.literal_eval for literal syntax while enforcing an application-specific shape and size limit.
Build and Parse Email Messages Offline
Construct a plain-text EmailMessage and parse its bytes while keeping transport separate.
Encode Binary Data with Python base64
Convert text to bytes before Base64 encoding and validate decoded input before using it.
Authenticate Messages with Python hmac
Sign a byte message with HMAC-SHA256 and verify it using a shared secret key.
Create Stable and Random UUIDs in Python
Build a reproducible UUID from a namespace and normalized name, and distinguish it from a random UUID.
Compress Text and Bytes with Python gzip
Compress UTF-8 text into gzip bytes and recover the original text.
Pack Binary Records with Python struct
Pack an unsigned identifier and status byte into a stable three-byte record.
Test Text Streams with Python StringIO
Pass a StringIO stream into a function and rewind it before a second read.
Read TOML Configuration with Python tomllib
Load a TOML configuration string and validate a required positive integer setting.
Find Files with Python glob and fnmatch
Select matching file names from a known list using fnmatchcase and deterministic sorting.
Benchmark Tiny Python Functions with timeit
Compute a per-call benchmark from repeated timeit runs without claiming universal speed.
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.
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.
Read and Write CSV with Quoting and Dialects
Read and write CSV records containing commas and quotation marks without splitting lines manually.
Serialize Datetime and Decimal Values to JSON
Serialize datetime and Decimal values to JSON with an explicit representation and reject unsupported types.
Write Clear CLI Output and Exit Codes
Separate successful CLI output from error diagnostics and return meaningful exit codes.
Parse Quoted Command Input with shlex
Parse a small command line while preserving quoted arguments and rejecting malformed input.
Test Binary Streams with io.BytesIO
Read a length-prefixed binary record from BytesIO and reject incomplete payloads.
Read Text Files with Explicit Encoding and Line Rules
Decode UTF-8 bytes and split lines consistently across LF, CRLF, and CR endings.
Find Month Boundaries with calendar.monthrange
Return the first and last date of a month, including leap-year February.
Parse and Format Timestamps with datetime
Validate a fixed UTC timestamp format before producing an ISO-style output string.
Calculate Quantiles and Percentiles with Python
Calculate and interpret inclusive quartiles for a numeric dataset with an explicit method.
Use Weighted Random Sampling in Python
Draw one outcome according to validated nonnegative weights using an injected random generator.
Validate JSON from HTTP Responses in Python
Validate an HTTP-like response's status, JSON syntax, and expected field types before using its data.
Retry Transient Failures with Timeouts and Backoff in Python
Retry only transient local failures with a bounded exponential delay schedule.
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.
Pillow Resize Image Without Losing Aspect Ratio
Resize an image into a maximum width and height without distortion, upscaling, or changing the original image.
Pandas GroupBy Multiple Columns with Named Aggregations
Summarize sales by region and product, with separate total amount and distinct order count columns.
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.
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 Create Temp File with NamedTemporaryFile
Create a UTF-8 temporary file, read it from the correct cursor position, and clean it up automatically.
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 argparse Subcommands with add_subparsers
Give add and list commands separate arguments and reject a missing or incomplete command.
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 subprocess.run Command: Capture Output Safely
Run a known local Python child process with separate arguments, capture output, and handle status and timeout.
Python zipfile extract: unpack selected files safely
Inspect ZIP members, allow only expected text files, and extract them into one chosen directory.
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.
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 cProfile example: find slow functions and read pstats
Profile a function, sort cumulative time, and distinguish call counts from elapsed time.
openpyxl read Excel in Python: rows, headers, and values
Read an .xlsx workbook with openpyxl and turn a sheet with headers into validated records.
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.
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.
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.
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.
Pandas to_datetime: Parse Dates and Find Invalid Rows
Convert date strings to UTC timestamps while identifying invalid or missing source values.
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.
Python re.findall: Return Full Matches Instead of Groups
Extract complete ERR- and WARN- codes without returning only captured prefixes or partial codes.
Pydantic field_validator: Normalize and Validate a Field
Normalize a handle before type validation while rejecting blank or non-string input.
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.
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.
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 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.
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
Practice graphs, dynamic programming, and efficient data processing.
Schedule Dependent Tasks with Topological Sort
Return tasks in an order that places every prerequisite before its dependent task.
Find a Shortest Unweighted Path with BFS
Return a shortest path in an unweighted adjacency-list graph using a FIFO queue.
Detect Directed Graph Cycles with DFS
Detect whether a directed adjacency-list graph contains a cycle.
Solve Coin Change with Dynamic Programming
Return the minimum number of positive-denomination coins for a target amount, or None if unreachable.
Compute a Moving Average with a Sliding Window
Return every fixed-size moving average with one pass and a running sum.
Count Connected Components with Union-Find
Count connected components in an undirected graph using a disjoint-set structure.
Answer Range Sum Queries with Prefix Sums
Build prefix totals and compute sums for half-open index ranges.
Understand Python Algorithmic Complexity with Measured Inputs
Measure how comparison counts grow for linear and binary search on increasing sorted inputs.
Solve Sorted-List Pair Sums with Two Pointers
Find a pair that reaches a target sum in a sorted list without testing every pair.
Find Combinations with Python Backtracking and Pruning
Generate unique positive-integer combinations that sum to a target while pruning impossible branches.