Python Learning Roadmap

From your first print("Hello") to a job-ready Python developer: 35 topics in four stages, each with what to learn, a short code example, free resources (official docs first), a hands-on task and, where it fits, practice problems on Exercism and LeetCode (74 in all). Written for Python 3.15 (the latest stable release is 3.15.2, October 2026); everything works on 3.12 and newer unless the text says otherwise. Learn the first three stages, then choose a path in stage 4: web development, data and machine learning, or automation and DevOps. Tick things off as you go; your progress is saved in this browser.

The roadmap in detail

Everything from the map above, on one page. Dashed topics are optional (in stage 4 that means "pick one path"). The hours are rough estimates for reading plus hands-on practice.

Stage 1 · Beginner Python foundations

Install Python, learn the core language and write small scripts that read files and handle errors. Type every example yourself; reading code is not the same as writing it.

Install Python, the REPL and running scripts

Install the current Python 3 from python.org (Windows and macOS installers) or your package manager on Linux, where a system Python is usually already there; don't remove or upgrade the system one, install another next to it. On Windows, the py launcher picks a version for you (py -3.15). Check with python3 --version (or python --version on Windows).

Typing python3 on its own opens the REPL (read–eval–print loop): type an expression, see the result at once. Since 3.13 the REPL has colours, multi-line editing and history. Real programs live in .py files that you run with python3 hello.py. Use an editor that understands Python: VS Code with the Python extension is free and the most common choice; PyCharm Community is another.

# hello.py — run it with: python3 hello.py
name = input("What is your name? ")
print(f"Hello, {name}!")

What to learn

  • Install Python 3 and check the version with python3 --version
  • Use the REPL for quick experiments; exit with exit() or Ctrl+D
  • Write a .py file and run it from the terminal
  • Set up VS Code with the Python extension and pick the interpreter
  • Use help() and dir() in the REPL to explore objects

Free resources

Practice

Install Python and VS Code, run the script above, then sign up on Exercism (free), install its CLI and submit Hello World.

Practice problems

Syntax, variables and basic types

Python uses indentation (four spaces by convention) instead of braces to group code, and a newline ends a statement. A variable is a name that points at an object; you don't declare its type, but every object has one: int (whole numbers of any size), float (64-bit binary floating point, so 0.1 + 0.2 is not exactly 0.3), bool (True/False) and None (no value).

Know the operators: / always gives a float, // is floor division (rounds towards minus infinity), % is the remainder and ** is power. Use == to compare values and is only for None (if x is None:). Empty strings, empty collections, 0 and None are "falsy" in an if. For money, use decimal.Decimal instead of floats.

print(7 / 2, 7 // 2, -7 // 2, 7 % 3, 2 ** 10)   # 3.5 3 -4 1 1024
print(0.1 + 0.2)                  # 0.30000000000000004
print(type(42), type(None))       # <class 'int'> <class 'NoneType'>
age = int("42")                   # convert text to a number

What to learn

  • Indentation, comments (#) and the PEP 8 naming style (snake_case)
  • int, float, bool, None and type()
  • Arithmetic: / vs //, %, **, and why floats are inexact
  • Comparison and boolean operators (and, or, not) and truthiness
  • Converting between types: int(), float(), str(), bool()

Free resources

Practice

Write a tip calculator: read a bill amount and a tip percentage with input(), convert them, and print the tip and the total rounded to two decimals.

Practice problems

Strings and f-strings

A str is an immutable sequence of Unicode characters. You can index (s[0], s[-1]) and slice (s[1:4], s[::-1]) it, loop over it and use dozens of methods: .strip(), .lower(), .split(), .join(), .replace(), .startswith(). Methods return a new string; the original never changes.

f-strings are the modern way to build text: f"{name} is {age}", with format specs such as {price:.2f}, {n:,} or {x!r}, and {x=} for quick debugging. Python 3.14 added t-strings (t"...", PEP 750), which look like f-strings but give a template object a library can process safely, for example to escape HTML or SQL; you'll meet them in libraries, not in everyday code yet.

name, price = "  Widget ", 1234.5
clean = name.strip().lower()
print(f"{clean!r} costs {price:,.2f}")   # 'widget' costs 1,234.50
print(", ".join(["a", "b", "c"]))        # a, b, c
print("python"[1:4], "python"[::-1])     # yth nohtyp

What to learn

  • Indexing, negative indexes and slicing [start:stop:step]
  • Common methods: strip, split, join, replace, find, lower/upper
  • f-strings with format specs (:.2f, :,, :>10) and {x=}
  • Strings are immutable; build big strings with "".join(parts)
  • Unicode, len(), in, and str vs bytes (.encode()/.decode())

Free resources

Practice

Write a function that turns " Hello World, from PYTHON " into a URL slug (hello-world-from-python), then print a small table of items and prices with columns lined up using f-string widths.

Practice problems

Lists, tuples, dicts and sets

The four built-in collections cover most needs. A list is an ordered, changeable sequence ([1, 2, 3]). A tuple is an ordered sequence you can't change ((x, y)), good for fixed records and dictionary keys. A dict maps keys to values ({"id": 1}) with fast lookup and keeps insertion order. A set holds unique items with fast membership tests and maths like union and intersection.

The most important idea: assignment never copies. b = a makes a second name for the same list, so changing b changes a. Copy with a.copy() or list(a) (shallow) or copy.deepcopy. Lookups with in are fast for dicts and sets and slow (they scan every item) for lists.

scores = {"ana": 91, "bo": 78}
scores["cy"] = 85
for name, score in scores.items():
    print(name, score)
print(scores.get("dan", 0))          # 0 instead of a KeyError
a = [1, 2]; b = a; b.append(3)
print(a)                             # [1, 2, 3]: same list
print({1, 2, 3} & {2, 3, 4})         # {2, 3}

What to learn

  • Lists: append, extend, insert, pop, sort vs sorted(), slicing
  • Tuples and unpacking (x, y = point, first, *rest = items)
  • Dicts: get, items, setdefault, merging with |, iterating
  • Sets: uniqueness, in, union |, intersection &, difference -
  • Mutable vs immutable, aliasing, shallow vs deep copies
  • Which collection to use, and the cost of in on a list vs a set

Free resources

Practice

Build a word-frequency counter: read a paragraph, lower-case it, split it into words, count them in a dict and print the ten most common. Then rewrite the counting with a set to list the unique words.

Practice problems

Control flow and loops

if / elif / else choose a branch; match (Python 3.10+) matches the shape of data, such as a command split into words or a dict from JSON. for loops go over any iterable (a list, a string, a dict's keys, a file's lines); use range() for counting, enumerate() when you need the index too and zip() to walk two lists side by side. while loops run until a condition is false.

break leaves a loop, continue skips to the next round, and a loop's else block runs only if the loop finished without break. Avoid for i in range(len(items)): looping over the items directly is shorter and clearer.

for i, fruit in enumerate(["apple", "kiwi"], start=1):
    print(i, fruit)

def handle(command):
    match command.split():
        case ["go", direction]:
            return f"going {direction}"
        case ["quit" | "exit"]:
            return "bye"
        case _:
            return "unknown command"

What to learn

  • if/elif/else and the conditional expression a if cond else b
  • for with range, enumerate and zip; while loops
  • break, continue and the loop else clause
  • Structural pattern matching with match/case
  • The walrus operator := (assign inside an expression), used sparingly

Free resources

Practice

Write a number-guessing game: the program picks a number with random.randint(1, 100), the player guesses until right, and the program says "higher" or "lower" and counts the guesses.

Practice problems

Comprehensions

A comprehension builds a list, dict or set from a loop in one expression: [x * x for x in nums if x > 0]. They are faster and clearer than appending in a loop, as long as they stay short. With round brackets you get a generator expression, which produces items one at a time instead of building the whole list (great inside sum(), any(), max()).

If a comprehension needs nested loops and conditions, or doesn't fit on one or two lines, write a normal loop. Python 3.15 also allows * and ** unpacking inside comprehensions (PEP 798), for example to flatten lists of lists.

nums = [3, -1, 4, -1, 5]
squares = [n * n for n in nums if n > 0]          # [9, 16, 25]
lengths = {word: len(word) for word in ["hi", "hello"]}
total = sum(n for n in nums if n > 0)             # 12, no list built
has_negative = any(n < 0 for n in nums)           # True

What to learn

  • List comprehensions with a filter
  • Dict and set comprehensions
  • Generator expressions with sum, any, all, max
  • When a plain loop is more readable

Free resources

Practice

Take a list of user dicts (name, age, active) and, with comprehensions only, build: the names of active users, a dict from name to age, and the set of distinct ages.

Practice problems

Functions and arguments

Define functions with def, return values with return (a function without one returns None) and document them with a docstring. Arguments can be passed by position or by name, and can have defaults. *args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dict; a bare * makes the following parameters keyword-only, which makes calls clearer.

The classic pitfall: default values are evaluated once, when the function is defined. A mutable default such as items=[] is shared by every call. Use None and create the list inside. Functions are objects: you can pass them to other functions, which is how sorted(key=…) and lambda work.

def add_item(item, items=None):
    """Append item to items (a new list if none is given)."""
    if items is None:
        items = []
    items.append(item)
    return items

def report(title, *values, sep=", ", **options):
    print(title, sep.join(map(str, values)), options)

report("Scores:", 3, 5, 8, sep=" | ", unit="pts")
people = [("ana", 31), ("bo", 25)]
print(sorted(people, key=lambda p: p[1]))   # youngest first

What to learn

  • def, return, docstrings, and functions returning None
  • Positional, keyword and default arguments; keyword-only (*) and positional-only (/)
  • *args and **kwargs, and unpacking a list/dict into a call
  • The mutable default argument pitfall and the None fix
  • Functions as values, lambda, and key= functions for sorted/max
  • Recursion basics (and Python's recursion limit)

Free resources

Practice

Refactor your earlier scripts into small functions with docstrings. Write stats(*numbers) that returns the min, max and mean, and call it with a list using stats(*my_list).

Practice problems

Scope, namespaces and closures

Python looks a name up in four places, in order: the Local function, any Enclosing functions, the module's Globals and the Built-ins (LEGB). Assigning to a name anywhere in a function makes it local to that function, for the whole function. That's why x += 1 inside a function fails with UnboundLocalError when x is a global.

Prefer passing values in and returning results over global. An inner function that uses variables from its enclosing function is a closure; it keeps them alive after the outer function returns, and nonlocal lets it change them. Closures are the building block of decorators.

def make_counter():
    count = 0
    def increment():
        nonlocal count
        count += 1
        return count
    return increment

tick = make_counter()
tick(); tick()
print(tick())   # 3

What to learn

  • The LEGB rule and what a namespace is
  • Why assigning inside a function makes a name local (UnboundLocalError)
  • global and nonlocal, and why to avoid global
  • Closures: inner functions that remember outer variables

Free resources

Practice

Write make_multiplier(n) that returns a function multiplying by n. Then reproduce an UnboundLocalError on purpose, read the message and fix it two ways (a parameter, then nonlocal in a closure).

Modules, packages and imports

Every .py file is a module; a folder of modules is a package (usually with an __init__.py). import math runs the module once and caches it; from pathlib import Path pulls one name in. Avoid from x import *: it hides where names come from. Python finds modules through sys.path, which starts with the folder of the script you ran.

Code at the top level of a module runs on import, so put a script's entry point under if __name__ == "__main__":; then the file works both as a program and as an importable module. Don't name your own files after standard modules (random.py, json.py): yours will be imported instead. Python 3.15 adds explicit lazy imports (PEP 810, lazy import x) that load a module only when it is first used, which speeds up the start of big command-line tools.

# greet.py
def greet(name):
    return f"Hello, {name}"

if __name__ == "__main__":      # only when run as a script
    print(greet("world"))

What to learn

  • import x, from x import y, import x as y
  • Packages, __init__.py, absolute vs relative imports
  • if __name__ == "__main__": and running with python -m package.module
  • How sys.path works and the "my file shadows a standard module" bug
  • Circular imports and how to break them

Free resources

Practice

Split your word counter into a package: textstats/__init__.py, textstats/counting.py and a textstats/__main__.py, then run it with python -m textstats file.txt.

Errors and exceptions

When something goes wrong Python raises an exception and prints a traceback; read it from the bottom (the error and message) up (where it happened). Catch exceptions you can actually handle with try/except SpecificError; let the rest crash loudly. else runs when nothing was raised and finally always runs, even after a return.

Never write a bare except: or swallow errors with pass: it hides bugs and even Ctrl+C. Raise your own errors with raise ValueError("…"), define custom exception classes for your library, and chain them with raise … from err so the original cause stays in the traceback. Python's style is EAFP: try the operation and handle the failure, rather than checking everything first.

class ConfigError(Exception):
    """Raised when the config file is missing or invalid."""

def read_port(text):
    try:
        port = int(text)
    except ValueError as err:
        raise ConfigError(f"port must be a number, got {text!r}") from err
    if not 0 < port < 65536:
        raise ConfigError(f"port out of range: {port}")
    return port

What to learn

  • Reading a traceback from the bottom up
  • try/except/else/finally, catching specific exceptions
  • Common built-in exceptions: ValueError, TypeError, KeyError, IndexError, FileNotFoundError
  • raise, custom exception classes and raise … from err
  • Why bare except: is dangerous; EAFP vs LBYL
  • Exception groups and except* (for concurrent code; know they exist)

Free resources

Practice

Make your tip calculator robust: keep asking until the input is a valid positive number, with a clear message for each mistake, and make sure Ctrl+C still quits.

Practice problems

Files, pathlib and context managers

Open files with with open(path, encoding="utf-8") as f:. The with statement is a context manager: it closes the file even if an error happens inside the block. Read a whole file with f.read(), or loop over f line by line for big files. Modes: "r" read, "w" overwrite, "a" append, "x" create only if missing, plus "b" for binary.

Use pathlib.Path instead of string paths: Path("data") / "report.csv" works on every OS, and paths have .exists(), .suffix, .read_text(), .glob("*.csv") and more. Always pass encoding="utf-8" for text; from Python 3.15 UTF-8 is the default everywhere (PEP 686), but older versions on Windows used the system code page. You can write your own context managers with contextlib.contextmanager.

from pathlib import Path

out = Path("reports")
out.mkdir(exist_ok=True)
for path in Path("logs").glob("*.log"):
    with path.open(encoding="utf-8") as f:
        errors = sum(1 for line in f if "ERROR" in line)
    (out / f"{path.stem}.txt").write_text(f"{errors} errors\n", encoding="utf-8")

What to learn

  • open() modes, encoding="utf-8", reading all vs line by line
  • with blocks and why they matter
  • pathlib.Path: joining, globbing, read_text/write_text, mkdir
  • Text vs binary files
  • Writing a context manager with @contextmanager

Free resources

Practice

Write a "tidy downloads" script: go through a folder and move each file into a subfolder named after its extension (pdf/, jpg/…), printing what it would do first with a --dry-run flag.

Practice problems

Am I ready? Stage 1 quiz

What does print(0.1 + 0.2 == 0.3) print?

  1. True
  2. False
  3. It raises an error
  4. None

Floats are binary fractions, so 0.1 + 0.2 is 0.30000000000000004. Compare floats with math.isclose(), or use Decimal for money.

After x = [1, 2, 3]; y = x; y.append(4), what is x?

  1. [1, 2, 3]
  2. [4]
  3. [1, 2, 3, 4]
  4. An error

Assignment doesn't copy: x and y are two names for the same list. Use x.copy() or list(x) to get a separate list.

What does print(7 // 2, -7 // 2) print?

  1. 3 -4
  2. 3 -3
  3. 3.5 -3.5
  4. 4 -4

// is floor division: it rounds towards minus infinity, so −3.5 becomes −4, not −3.

Given def add(item, items=[]): items.append(item); return items, what does add(1); print(add(2)) print?

  1. [2]
  2. [1]
  3. An error
  4. [1, 2]

The default list is created once, when the function is defined, and shared by every call. Use items=None and create the list inside.

With x = 10 at module level, what happens when you call def f(): x += 1?

  1. The global x becomes 11
  2. UnboundLocalError
  3. A local x becomes 1
  4. NameError

Assigning to x anywhere in f makes it a local name, and it is read before it has a value. Pass it in and return the result instead (or use global, rarely).

Stage 2 · Intermediate Writing real programs

Organise code with classes, use the language's power features, lean on the standard library and set up projects the way professional teams do: virtual environments, tests, a linter and a debugger.

Classes and object-oriented programming

A class bundles data (attributes) with the functions that work on it (methods). __init__ sets up a new object, and self is the object a method was called on. Class attributes are shared by all instances; instance attributes belong to one object. @property lets you add validation or computed values without changing how callers read the attribute, and @classmethod is handy for alternative constructors (Date.from_string(…)).

Inheritance (class Admin(User)) reuses and extends behaviour, and super() calls the parent's version of a method. Prefer composition (an object has another object) when the relationship isn't truly "is a"; deep inheritance trees are hard to change. Python has no private attributes; a leading underscore (_balance) means "internal, don't touch".

class Account:
    interest_rate = 0.02                  # shared by all accounts

    def __init__(self, owner, balance=0):
        self.owner = owner
        self._balance = balance

    @property
    def balance(self):
        return self._balance

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("deposit must be positive")
        self._balance += amount

class SavingsAccount(Account):
    interest_rate = 0.04

    def add_interest(self):
        self.deposit(self.balance * self.interest_rate)

What to learn

  • Classes, instances, __init__ and self
  • Instance vs class attributes; @property, @classmethod, @staticmethod
  • Inheritance, method overriding and super()
  • Composition over inheritance, and when each fits
  • Abstract base classes (abc.ABC) and typing.Protocol for interfaces
  • Naming conventions: _internal and name mangling with __private

Free resources

Practice

Model a small library: Book, Member and Library classes, where members borrow and return books, with an error when a book is already out. Use composition (a library has books), not inheritance.

Practice problems

Dunder methods, dataclasses and enums

"Dunder" (double underscore) methods let your objects work with Python's syntax: __repr__ for a useful debug view, __eq__ and __lt__ for comparisons, __len__, __iter__ and __getitem__ to behave like a collection, __add__ for +, __enter__/__exit__ for with. This is the data model, and it's why len() works on everything.

For classes that mostly hold data, @dataclass writes __init__, __repr__ and __eq__ for you from type-annotated fields; add frozen=True for immutable objects, order=True for sorting and slots=True to save memory. Use enum.Enum for a fixed set of named values (statuses, colours) instead of bare strings. Python 3.15 also adds a built-in, immutable frozendict (PEP 814).

from dataclasses import dataclass, field
from enum import Enum

class Status(Enum):
    TODO = "todo"
    DONE = "done"

@dataclass(order=True)
class Task:
    priority: int
    title: str = field(compare=False)
    status: Status = field(default=Status.TODO, compare=False)

tasks = sorted([Task(2, "write tests"), Task(1, "fix bug")])
print(tasks[0])   # Task(priority=1, title='fix bug', status=<Status.TODO: 'todo'>)

What to learn

  • __repr__ vs __str__, __eq__ and __hash__
  • Making a class iterable or sized (__iter__, __len__, __getitem__)
  • Operator overloading (__add__, __lt__) and functools.total_ordering
  • @dataclass with defaults, field(default_factory=list), frozen, order, slots
  • enum.Enum and enum.StrEnum

Free resources

Practice

Write a Money dataclass (amount as Decimal, currency) that supports + between the same currency, raises an error for different currencies, sorts correctly and prints nicely.

Practice problems

Iterators and generators

An iterable is anything a for loop can walk over; behind the scenes Python calls iter() to get an iterator and next() until it raises StopIteration. An iterator is used up after one pass.

A generator function uses yield instead of return: each yield hands back one value and pauses until the next one is asked for. Generators produce items lazily, so you can process a 10 GB log file or an endless stream in constant memory, and chain steps into a pipeline. yield from delegates to another iterable.

def read_errors(lines):
    for line in lines:
        if "ERROR" in line:
            yield line.rstrip()

def first(n, items):
    for i, item in enumerate(items):
        if i == n:
            return
        yield item

logs = ["ok\n", "ERROR disk\n", "ERROR net\n", "ERROR cpu\n"]
print(list(first(2, read_errors(logs))))   # ['ERROR disk', 'ERROR net']

What to learn

  • Iterable vs iterator, iter(), next() and StopIteration
  • Generator functions with yield, and generator expressions
  • Why a generator can only be consumed once
  • Lazy pipelines and processing large files in constant memory
  • yield from

Free resources

Practice

Write a generator that reads a large CSV file line by line and yields only the rows matching a filter, then a second generator that groups them into batches of 100. Check memory stays flat with a file of a million lines.

Practice problems

Decorators

A decorator is a function that takes a function and returns a new one, usually wrapping the original with extra behaviour: timing, logging, caching, retrying, checking permissions. @timer above a def is just shorthand for func = timer(func). Web frameworks use them everywhere (@app.get("/")), and so does the standard library (@property, @functools.cache, @dataclass).

Always decorate the wrapper with @functools.wraps(func); without it the decorated function loses its name and docstring, which breaks debugging and tools. A decorator that takes arguments (@retry(times=3)) is a function that returns a decorator.

import functools
import time

def timer(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        try:
            return func(*args, **kwargs)
        finally:
            print(f"{func.__name__} took {time.perf_counter() - start:.3f}s")
    return wrapper

@timer
def slow_sum(n):
    return sum(range(n))

slow_sum(1_000_000)

What to learn

  • Functions as arguments and return values (higher-order functions)
  • Writing a decorator with *args, **kwargs and functools.wraps
  • Decorators with arguments (a decorator factory)
  • Built-in decorators: @property, @classmethod, @staticmethod, @functools.cache
  • Stacking decorators and the order they apply in

Free resources

Practice

Write @retry(times=3, delay=0.5) that re-runs a function when it raises, waiting between tries, and re-raises after the last failure. Test it with a function that fails randomly.

Practice problems

Type hints and mypy

Type hints (def greet(name: str) -> str:) document what a function expects and returns. Python itself ignores them at run time, but editors use them for autocompletion and a type checker such as mypy (or Pyright, used by VS Code's Pylance) finds bugs before you run the code: passing None where a string is needed, a typo in an attribute, a missing return. Libraries such as FastAPI and Pydantic read hints at run time to validate data.

Modern syntax: built-in generics (list[int], dict[str, float]), unions with | (int | None), type aliases (3.12+) and generic functions with def first[T](items: list[T]) -> T (3.12+). Since Python 3.14, annotations are evaluated lazily (PEP 649), so classes can refer to themselves or to classes defined later without quotes. Add hints to function signatures first; you rarely need them on local variables.

from typing import Protocol

type UserId = int

class Greeter(Protocol):
    def greet(self, name: str) -> str: ...

def find_user(users: dict[UserId, str], user_id: UserId) -> str | None:
    return users.get(user_id)

def first[T](items: list[T]) -> T:
    return items[0]

What to learn

  • Annotating parameters, return values and attributes
  • list[int], dict[str, int], X | None, Callable, Iterable
  • Protocol (structural typing), TypedDict and Literal
  • Generics with the 3.12+ syntax and type aliases
  • Running mypy (or Pyright) and fixing what it finds; gradual typing

Free resources

Practice

Add type hints to your library project, run mypy --strict and fix every error. Note at least one real bug it found.

The standard library tour

Python comes "batteries included": before installing a package, check the standard library. The modules you'll use constantly: collections (Counter, defaultdict, deque, namedtuple), itertools (chain, groupby, product, combinations, batched), functools (cache, partial, reduce), datetime and zoneinfo (always store times with a time zone), json and csv, re for regular expressions, logging, argparse for command-line options, plus random, statistics, secrets, subprocess, shutil and tomllib.

Learn what each one is for rather than every function; the docs are excellent once you know where to look. Use logging instead of print in anything that runs unattended, and secrets (not random) for tokens and passwords.

import json
import re
from collections import Counter
from datetime import datetime, timezone

text = "error: disk full; warn: slow; error: timeout"
levels = Counter(re.findall(r"(\w+):", text))
print(levels.most_common(1))           # [('error', 2)]
stamp = datetime.now(timezone.utc).isoformat()
print(json.dumps({"at": stamp, "counts": levels}, indent=2))

What to learn

  • collections: Counter, defaultdict, deque
  • itertools and functools basics
  • datetime with time zones (zoneinfo), parsing and formatting
  • json and csv: reading and writing
  • re: search, findall, groups, and raw strings r"…"
  • logging (levels, handlers, formatters) and argparse

Free resources

Practice

Build a log analyser CLI: python logstats.py access.log --top 10 --since 2026-10-01. Parse lines with re, count status codes and paths with Counter, filter by date with datetime, output a table or --json, and log progress with logging.

Practice problems

Virtual environments and installing packages

Every project should have its own virtual environment: a folder with its own Python and its own installed packages, so project A can use Django 5 while project B uses Django 6, and nothing pollutes the system Python (many Linux distributions now refuse pip install into it). Create one with python3 -m venv .venv, activate it, and install packages from PyPI with pip install requests.

Record dependencies so others can reproduce your setup: the modern place is the [project] dependencies list in pyproject.toml, with a lock file (or pip freeze > requirements.txt) pinning exact versions for apps. Tools that manage all of this for you are popular: uv (very fast; installs Python itself, creates the venv and locks dependencies) and Poetry; plain venv + pip is still fine and is what every tool builds on. Don't commit the .venv folder.

# In a terminal (shown as comments):
# python3 -m venv .venv
# source .venv/bin/activate      (Windows: .venv\Scripts\activate)
# pip install requests
# pip freeze > requirements.txt
import sys
print(sys.prefix)   # points inside .venv when the environment is active

What to learn

  • Why virtual environments exist; create and activate one with venv
  • pip install, pip list, pip install -U, pip uninstall
  • requirements.txt vs pyproject.toml dependencies, and pinning with a lock file
  • Version specifiers (>=2.31,<3) and semantic versioning
  • What uv and Poetry add; pick one tool per project
  • Add .venv/ to .gitignore

Free resources

Practice

Put your log analyser in a Git repository with a venv, a pyproject.toml listing rich as a dependency and a README with setup steps. Clone it into a new folder and check the steps work from scratch.

Testing with pytest

Automated tests let you change code without fear. pytest is the standard choice: write functions named test_* in files named test_*.py, use plain assert, and run pytest. When an assert fails, pytest shows the values involved. pytest.raises checks that an error is raised, @pytest.mark.parametrize runs one test over many inputs, and fixtures provide set-up (a temporary folder, a test database, a client) to any test that asks for one by name.

Mocking (unittest.mock, or pytest's monkeypatch) replaces slow or external things such as HTTP calls and the clock during a test. Mock at the boundaries of your code, not everything, or your tests only test the mocks. Measure what your tests run with pytest-cov. The standard library's unittest also works, and pytest runs those tests too.

# test_money.py — run with: pytest
import pytest
from slugify_util import slugify

@pytest.mark.parametrize("text, expected", [
    ("Hello World", "hello-world"),
    ("  Python 3.15! ", "python-3-15"),
])
def test_slugify(text, expected):
    assert slugify(text) == expected

def test_slugify_rejects_empty():
    with pytest.raises(ValueError):
        slugify("")

def test_writes_file(tmp_path):        # tmp_path is a built-in fixture
    out = tmp_path / "out.txt"
    out.write_text("hi")
    assert out.read_text() == "hi"

What to learn

  • Writing and running pytest tests; reading the failure output
  • pytest.raises and @pytest.mark.parametrize
  • Fixtures, built-in ones (tmp_path, monkeypatch, capsys) and conftest.py
  • Mocking with unittest.mock.patch, and where to patch
  • Coverage with pytest-cov; unit vs integration tests

Free resources

Practice

Write tests for your log analyser: parametrized tests for the line parser, a test using tmp_path with a small sample log, and a test for bad input. Reach 90% coverage. Exercism already uses pytest, so run its tests locally too.

Code style, linting and formatting

Teams don't argue about formatting; they let tools do it. PEP 8 is the style guide (4-space indents, snake_case functions, CapWords classes, readable line lengths). A formatter rewrites your code into one consistent style: Black or Ruff's formatter (ruff format, Black-compatible). A linter finds likely bugs and bad patterns: Ruff (ruff check) is fast and replaces Flake8, isort and many plugins.

Configure them in pyproject.toml, run them in your editor on save, in a pre-commit hook and in CI so nothing unformatted gets merged. Read "The Zen of Python" (import this): readability counts.

# pyproject.toml settings, shown as comments:
# [tool.ruff]
# line-length = 100
# [tool.ruff.lint]
# select = ["E", "F", "I", "B", "UP"]
import this   # prints the Zen of Python

What to learn

  • PEP 8 naming and layout; PEP 257 docstrings
  • Format with ruff format or Black; lint with ruff check --fix
  • Configuring tools in pyproject.toml
  • pre-commit hooks so checks run before each commit
  • Format and lint in your editor on save

Free resources

Practice

Add Ruff (lint + format) and mypy to your project with pre-commit, fix everything they report, and commit the configuration.

Debugging

Stop guessing and look. Read the whole traceback, reproduce the bug with the smallest input you can, then inspect what the code is really doing. Put breakpoint() in your code to drop into pdb: n runs the next line, s steps into a call, p expr prints a value, c continues. python -m pdb script.py starts a script under the debugger, and pytest --pdb opens it at a failing test.

An editor debugger (VS Code) does the same with clicks: breakpoints, variables, the call stack and conditional breakpoints. For problems in production, good logging with context (ids, inputs) beats a debugger. When you find a bug, write a test that reproduces it before fixing it.

def average(values):
    total = sum(values)
    breakpoint()           # pauses here: try "p total", "p len(values)", "c"
    return total / len(values)

What to learn

  • Reading tracebacks, including chained ones ("During handling of…")
  • breakpoint() and pdb commands (n, s, p, l, c, q)
  • The VS Code debugger: breakpoints, watches, stepping
  • pytest --pdb and pytest -x
  • Shrinking a bug to a minimal reproduction, then writing a test for it

Free resources

Practice

Call average([]) from the example, find the crash with pdb, then fix it and add a test for the empty list.

Am I ready? Stage 2 quiz

What does this print? gen = (n * n for n in range(3)); print(sum(gen), sum(gen))

  1. 5 5
  2. 14 14
  3. 5 0
  4. An error

0 + 1 + 4 = 5. A generator is used up after one pass, so the second sum sees nothing and returns 0.

With @dataclass class P: x: int; y: int = 0, what is P(1) == P(1, 0)?

  1. True, because dataclasses compare their fields
  2. False, because they are different objects
  3. An error: dataclasses can't be compared
  4. True only if frozen=True

@dataclass writes __eq__ for you, comparing the fields as tuples: (1, 0) == (1, 0).

A decorator returns an inner wrapper function but doesn't use functools.wraps. What is the decorated hello.__name__?

  1. 'hello'
  2. 'deco'
  3. None
  4. 'wrapper'

The name now points at the wrapper, so its name and docstring are lost. @functools.wraps(func) copies them over.

Why give each project its own virtual environment?

  1. It makes Python run faster
  2. Each project gets its own package versions without clashing with others or the system Python
  3. pip only works inside one
  4. It is needed to use type hints

A venv isolates installed packages per project, so upgrading a library for one project can't break another, and the system Python stays clean.

In pytest, how do you give a test a fresh temporary folder?

  1. Call os.mkdir("/tmp/test") at the top of the file
  2. Use unittest.mock.patch
  3. Add a tmp_path parameter; pytest passes a new folder as a fixture
  4. Create it in conftest.py as a global variable

tmp_path is a built-in fixture: name it as a parameter and pytest injects a unique pathlib.Path for that test.

Stage 3 · Advanced Python in production

Talk to the outside world (HTTP APIs and databases), do many things at once, package your code for others and make it fast where it matters. This is the bridge from scripts to real services.

HTTP requests and JSON APIs

Most programs talk to web APIs. requests is the classic, simple library; httpx has a very similar API and adds async support and HTTP/2. The standard library's urllib.request works without installing anything but is clunkier. A request has a method (GET, POST…), a URL, headers and maybe a JSON body; the response has a status code, headers and a body you usually decode with .json().

Production habits: always set a timeout (requests waits forever by default), call raise_for_status() to turn 4xx/5xx into exceptions, reuse a Session/Client for connection pooling, retry only safe requests with backoff, and keep API keys in environment variables, never in code.

import os
import requests

session = requests.Session()
session.headers["Authorization"] = f"Bearer {os.environ.get('API_TOKEN', '')}"

resp = session.get("https://api.github.com/repos/python/cpython", timeout=10)
resp.raise_for_status()
repo = resp.json()
print(repo["full_name"], repo["stargazers_count"])

What to learn

  • HTTP basics: methods, status codes, headers, JSON bodies
  • requests/httpx: GET/POST, params, JSON, headers, sessions
  • Timeouts, raise_for_status(), retries with backoff
  • Authentication (API keys, bearer tokens) from environment variables
  • Pagination and rate limits (429 and Retry-After)

Free resources

Practice

Write a script that lists a GitHub user's public repositories (following pagination), sorts them by stars and saves the result as JSON and CSV. Handle a missing user and the rate limit gracefully.

Practice problems

Databases from Python

Python ships with sqlite3, a full SQL database in a single file, perfect for learning, tests and small apps. Every database driver follows the same DB-API pattern: connect, get a cursor, execute SQL, fetch rows, commit. For PostgreSQL use psycopg (version 3).

The rule you must never break: pass values as parameters (execute("… WHERE email = ?", (email,))), never build SQL with f-strings, or you have an SQL injection hole. Bigger apps use SQLAlchemy (a SQL toolkit and ORM) or the Django ORM, with migrations (Alembic) to change the schema safely. Learn SQL itself first; an ORM doesn't replace it.

import sqlite3

with sqlite3.connect("app.db") as conn:      # commits on success
    conn.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, email TEXT UNIQUE)")
    email = "ana@example.com"
    conn.execute("INSERT OR IGNORE INTO users (email) VALUES (?)", (email,))
    row = conn.execute("SELECT id, email FROM users WHERE email = ?", (email,)).fetchone()
    print(row)

What to learn

  • sqlite3: connect, execute, fetch, commit, rollback
  • Parameterised queries and why f-string SQL is an injection risk
  • psycopg for PostgreSQL and connection handling
  • SQLAlchemy Core and ORM basics, sessions, and the N+1 query problem
  • Schema migrations with Alembic

Free resources

Practice

Store your GitHub repositories script's results in SQLite (tables for users and repos), then answer "top 5 languages by total stars" with one SQL query. Do the SQL roadmap's first stage alongside.

Concurrency: threads, processes and asyncio

First decide what kind of waiting you have. I/O-bound work (HTTP calls, database queries, files) spends its time waiting; threads (concurrent.futures.ThreadPoolExecutor) or asyncio let many waits overlap. CPU-bound work (number crunching in pure Python) needs several CPU cores at once, which in standard CPython means processes (ProcessPoolExecutor, multiprocessing), because of the GIL (global interpreter lock): only one thread runs Python bytecode at a time.

That is changing. Python 3.13 added an optional free-threaded build without the GIL (PEP 703, experimental then); since 3.14 it is officially supported (PEP 779), but it is still a separate build (for example python3.14t) and the default build still has the GIL. asyncio runs many tasks on one thread: async def functions await slow operations, and asyncio.gather or a TaskGroup runs them concurrently. It shines for thousands of network connections, but one blocking call (like time.sleep or requests.get) freezes every task.

import asyncio

async def fetch(name, delay):
    await asyncio.sleep(delay)          # stands in for a network call
    return f"{name} done"

async def main():
    async with asyncio.TaskGroup() as tg:
        tasks = [tg.create_task(fetch(f"job{i}", 1)) for i in range(3)]
    print([t.result() for t in tasks])  # all three finish in about 1 second

asyncio.run(main())

What to learn

  • I/O-bound vs CPU-bound work, and concurrency vs parallelism
  • concurrent.futures: thread and process pools, map and as_completed
  • The GIL, what it does and doesn't block, and free-threaded builds
  • async/await, asyncio.run, gather, TaskGroup, timeouts
  • Never block the event loop; async libraries (httpx, asyncpg)
  • Race conditions, locks and queues

Free resources

Practice

Download 50 web pages three ways (a loop, a thread pool, asyncio with httpx) and time each. Then compute primes up to 5 million with a loop vs a process pool, and explain the results.

Project structure and packaging

A real project has a predictable layout: a src/yourpackage/ folder, tests/, a README.md, a licence and a pyproject.toml that holds the name, version, dependencies, entry points and tool settings. The src layout makes sure your tests run against the installed package, not loose files.

Build a wheel (the installable format) with a build backend such as Hatchling or setuptools (python -m build, or uv build) and publish it to PyPI (try TestPyPI first) with twine or uv publish. A [project.scripts] entry turns a function into a command people can run after pip install. Even if you never publish, pip install -e . (an editable install) is how you work on your own package.

# pyproject.toml, shown as comments:
# [project]
# name = "logstats"
# version = "0.1.0"
# requires-python = ">=3.12"
# dependencies = ["rich>=13"]
# [project.scripts]
# logstats = "logstats.cli:main"
# [build-system]
# requires = ["hatchling"]
# build-backend = "hatchling.build"
import tomllib
with open("pyproject.toml", "rb") as f:
    print(tomllib.load(f)["project"]["name"])

What to learn

  • The src layout and where tests, docs and config live
  • pyproject.toml: [project], dependencies, optional dependencies, [build-system]
  • Editable installs (pip install -e .)
  • Console scripts via [project.scripts]
  • Building wheels and publishing to TestPyPI, then PyPI

Free resources

Practice

Turn your log analyser into an installable package with the src layout and a logstats command, build a wheel, install it in a fresh venv and run it. Optionally publish it to TestPyPI.

Performance and profiling

Measure before optimising: the slow part is rarely where you guess. timeit times small snippets; cProfile (python -m cProfile -s cumulative app.py) shows where a whole program spends its time. Python 3.15 adds a profiling package with a new low-overhead sampling profiler, Tachyon (PEP 799), and tools such as py-spy can sample a running process.

The biggest wins are usually algorithmic: a set or dict instead of searching a list, avoiding repeated work with functools.cache, generators instead of huge lists, and batching database or HTTP calls. Built-ins and libraries written in C (NumPy, pandas) are far faster than Python loops over the same data. Recent CPython releases are also faster on their own, and there is an experimental JIT compiler; upgrading Python is a free speed-up.

import timeit

setup = "items = list(range(10_000)); as_set = set(items)"
print(timeit.timeit("9_999 in items", setup=setup, number=1_000))    # scans the list
print(timeit.timeit("9_999 in as_set", setup=setup, number=1_000))   # hash lookup, far faster

What to learn

  • timeit for micro-benchmarks
  • cProfile and reading its output; sampling profilers
  • Big-O of list, dict and set operations
  • Caching with functools.cache/lru_cache
  • When to reach for NumPy, multiprocessing or a compiled extension

Free resources

Practice

Profile your log analyser on a 1-million-line file, find the slowest function, speed it up at least 3× and prove it with numbers before and after.

Am I ready? Stage 3 quiz

You must run a pure-Python, CPU-heavy calculation on all 8 cores with the standard CPython build. What do you use?

  1. ThreadPoolExecutor
  2. ProcessPoolExecutor (or multiprocessing)
  3. asyncio.gather
  4. A bigger for loop

The GIL lets only one thread run Python bytecode at a time, so threads and asyncio don't add CPU parallelism there. Separate processes each have their own interpreter and GIL.

Three coroutines each await asyncio.sleep(1) and are run together with asyncio.gather. About how long does it take?

  1. About 1 second
  2. About 3 seconds
  3. It never finishes
  4. About 0 seconds

While one task awaits, the event loop runs the others, so the three waits overlap. With time.sleep instead, they would block the loop and take 3 seconds.

Which line safely looks up a user by an email typed into a form?

  1. cur.execute(f"SELECT * FROM users WHERE email = '{email}'")
  2. cur.execute("SELECT * FROM users WHERE email = '" + email + "'")
  3. cur.execute("SELECT * FROM users WHERE email = '%s'" % email)
  4. cur.execute("SELECT * FROM users WHERE email = ?", (email,))

Only a parameterised query keeps the value separate from the SQL. The other three paste user input into the SQL text, which allows SQL injection.

What happens with requests.get(url) if the server accepts the connection but never answers?

  1. It gives up after 30 seconds
  2. It raises at once
  3. It can wait forever, because there is no default timeout
  4. It retries three times

requests has no default timeout. Always pass timeout= (for example timeout=10) in real code.

Where do a modern Python project's name, dependencies and tool settings belong?

  1. setup.cfg only
  2. pyproject.toml
  3. requirements.txt
  4. __init__.py

pyproject.toml is the standard file (PEP 518/621) for project metadata, build settings and tool configuration such as Ruff, mypy and pytest.

Stage 4 · Specialise Choose your path

Python is used for very different jobs. Pick one path and go deep before trying another: web development, data and machine learning, or automation and DevOps. The path topics are marked optional so the progress bar doesn't ask you to learn all of them; use the filter at the top to show only your path. Everyone finishes with the job-ready topic.

Web: Flask

Flask is a small web framework: you map URLs to Python functions with @app.route, read the request, and return HTML (rendered with Jinja templates) or JSON. It gives you only the core and lets you choose extensions for databases, forms and logins, which makes it a great way to understand how web apps work.

Learn the request/response cycle, routing with variables, templates, forms, sessions, blueprints to split an app, and an application factory for configuration and tests. Run it in production behind a real WSGI server such as Gunicorn, never with the built-in development server.

from flask import Flask, jsonify, request

app = Flask(__name__)
todos = []

@app.get("/todos")
def list_todos():
    return jsonify(todos)

@app.post("/todos")
def add_todo():
    todo = {"id": len(todos) + 1, "title": request.json["title"]}
    todos.append(todo)
    return todo, 201

What to learn

  • Routes, HTTP methods, URL variables and returning JSON
  • Jinja templates, static files and forms
  • Blueprints and the application factory pattern
  • A database with SQLAlchemy (Flask-SQLAlchemy) and migrations
  • Testing with Flask's test client; deploying with Gunicorn

Free resources

Practice

Do the official Flask tutorial, then build a link-shortener API with SQLite, tests and a Dockerfile. The Backend roadmap covers what comes next: auth, caching, queues and deployment.

Web: Django

Django is the "batteries included" framework: an ORM with migrations, an automatic admin site, authentication, forms, templates, security protections (CSRF, XSS, SQL injection) and a huge ecosystem. It's the common choice for content sites, internal tools and SaaS back ends where you want to move fast with conventions.

Learn the project/app structure, models and migrations, the ORM's querysets, views and URLs, templates, the admin, and users and permissions. Watch out for the N+1 query problem: use select_related (foreign keys) and prefetch_related (many-to-many and reverse relations). For APIs, add Django REST Framework or Django Ninja.

# models.py in a Django app
from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

# One query with a JOIN instead of one extra query per book:
# Book.objects.select_related("author")

What to learn

  • Projects vs apps, settings and manage.py
  • Models, migrations and the ORM (filter, annotate, aggregates)
  • Views, URLs, templates and forms
  • The admin site, users, authentication and permissions
  • Query optimisation (select_related, prefetch_related) and REST APIs with DRF

Free resources

Practice

Do the official polls tutorial, then build a small job board: companies, job posts, an admin to manage them, user sign-up and a search page. Use Django Debug Toolbar to count queries on each page and remove any N+1.

Web: FastAPI and REST APIs

FastAPI builds APIs from type hints: declare parameters and Pydantic models, and it validates requests, converts types, returns clear 422 errors and generates interactive OpenAPI docs at /docs. It supports async def endpoints, so it fits services that call other APIs or databases a lot.

Learn path and query parameters, request and response models, dependency injection (Depends) for database sessions and auth, status codes and error handling, background tasks, and testing with its TestClient. Run it with an ASGI server such as Uvicorn. REST design rules (resources, methods, status codes, pagination) apply whatever framework you use.

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    price: float

items: dict[int, Item] = {}

@app.post("/items/{item_id}", status_code=201)
def create_item(item_id: int, item: Item) -> Item:
    if item_id in items:
        raise HTTPException(status_code=409, detail="item exists")
    items[item_id] = item
    return item

What to learn

  • Path/query parameters and Pydantic request/response models
  • Validation errors, status codes and HTTPException
  • Dependencies (Depends) for database sessions and auth
  • The generated OpenAPI docs; sync vs async endpoints
  • Testing with TestClient; running with Uvicorn

Free resources

Practice

Build a notes API with FastAPI, SQLAlchemy and SQLite: CRUD endpoints, pagination, JWT login and tests. Then follow the Backend roadmap's REST topic and auth topic.

Data: NumPy and pandas

NumPy gives you fast n-dimensional arrays: operations apply to every element at once (vectorised) and run in C, so they're far faster than Python loops. pandas builds on it with the DataFrame, a table with labelled columns, and tools to load CSV, Excel, JSON, SQL and Parquet, clean messy data, filter, group, join and reshape it.

Learn to think in columns, not loops: boolean masks for filtering, groupby + agg for summaries, merge for joins (just like SQL), and handling missing values (isna, fillna, dropna). Use .loc for label-based selection to avoid "SettingWithCopy" surprises. Polars and DuckDB are fast alternatives worth knowing about once pandas feels comfortable.

import numpy as np
import pandas as pd

prices = np.array([10.0, 12.5, 9.0])
print(prices * 1.2)                        # every element, no loop

df = pd.DataFrame({
    "city": ["Pune", "Delhi", "Pune", "Delhi"],
    "sales": [120, 90, 150, 60],
})
print(df[df["sales"] > 80])                # filter rows with a mask
print(df.groupby("city")["sales"].sum())   # Delhi 150, Pune 270

What to learn

  • NumPy arrays, shapes, vectorised maths and broadcasting
  • pandas Series and DataFrames; reading CSV/Excel/SQL
  • Selecting with .loc/.iloc and boolean masks
  • Cleaning: types, missing values, duplicates, string and date columns
  • groupby/agg, merge, pivot_table

Free resources

Practice

Download a public dataset (for example a city's open data portal or a Kaggle CSV), clean it, and answer five questions with pandas: totals per category, trends per month, the top 10, and one join with a second dataset. Compare one answer with the same query in SQL.

Data: Jupyter and visualisation

Jupyter notebooks mix code, results, charts and notes in one document, which is how most data exploration is done; JupyterLab and VS Code both open .ipynb files. Run cells top to bottom and restart the kernel often, because cells run out of order are the classic notebook bug. Move code you reuse into normal .py modules.

Matplotlib is the foundation for charts in Python (line, bar, scatter, histogram), and pandas plots through it with df.plot(). seaborn adds statistical charts with good defaults, and Plotly makes interactive ones. Choose the chart for the question: trends over time → line, comparing categories → bar, relationships → scatter, distributions → histogram.

import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr"]
sales = [120, 135, 128, 160]

fig, ax = plt.subplots(figsize=(6, 3))
ax.plot(months, sales, marker="o")
ax.set_title("Monthly sales")
ax.set_ylabel("Units")
fig.tight_layout()
fig.savefig("sales.png", dpi=150)

What to learn

  • Jupyter notebooks: cells, kernel, Markdown notes, restarting cleanly
  • Matplotlib figures and axes; line, bar, scatter and histogram
  • Plotting from pandas with df.plot()
  • Labels, titles, legends, and choosing the right chart
  • Saving charts and sharing notebooks

Free resources

Practice

Turn your pandas analysis into a clean notebook that tells a story: a question at the top, five charts with one sentence of insight each, and a conclusion. Restart and run all before sharing.

Data: machine learning with scikit-learn

scikit-learn is the standard library for classic machine learning: every model has the same fit / predict interface. Learn the workflow before the algorithms: split the data into training and test sets, build a pipeline (preprocessing + model), train, and evaluate on data the model hasn't seen, with the right metric (accuracy, precision/recall, mean absolute error).

Start with linear and logistic regression, decision trees and random forests; learn cross-validation, overfitting, feature scaling and encoding categories. Deep learning (PyTorch) and LLM applications build on these ideas; get the basics solid first, then continue with the AI Engineering roadmap.

from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split

X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)
model = RandomForestClassifier(random_state=0).fit(X_train, y_train)
print(f"accuracy: {model.score(X_test, y_test):.2f}")

What to learn

  • Supervised vs unsupervised learning; classification vs regression
  • Train/test split, cross-validation and overfitting
  • Pipelines with preprocessing (scaling, one-hot encoding)
  • Linear/logistic regression, decision trees, random forests
  • Choosing and reading metrics

Free resources

Practice

Predict house prices or customer churn from a public dataset: a baseline first (always predict the average), then a pipeline with two models compared by cross-validation, and a short write-up of what the model gets wrong.

Automation and scripting

Python is the best "glue" language: rename a thousand files, fill in spreadsheets, send reports, call APIs, and run other programs with subprocess.run([...], check=True) (pass a list, not a shell string). Make scripts into proper command-line tools with argparse (or Typer/Click), clear --help, a --dry-run option and useful exit codes.

Web scraping (requests + Beautiful Soup, or Playwright for JavaScript-heavy pages) is powerful but has rules: prefer an official API, read the site's terms, respect robots.txt, go slowly and identify your bot. Schedule scripts with cron or systemd timers on Linux, Task Scheduler on Windows, or a scheduled CI job.

import argparse
import subprocess
from urllib.robotparser import RobotFileParser

parser = argparse.ArgumentParser(description="Back up a folder with tar")
parser.add_argument("folder")
parser.add_argument("--dry-run", action="store_true")
args = parser.parse_args()

cmd = ["tar", "-czf", "backup.tar.gz", args.folder]
if args.dry_run:
    print("would run:", " ".join(cmd))
else:
    subprocess.run(cmd, check=True)

robots = RobotFileParser("https://example.com/robots.txt")
robots.read()
print(robots.can_fetch("my-bot", "https://example.com/page"))

What to learn

  • Files and folders at scale: pathlib, shutil, glob
  • Running commands with subprocess.run safely
  • CLI tools with argparse (or Typer), exit codes and --dry-run
  • Scraping with requests + Beautiful Soup, and its ethics (API first, robots.txt, rate limits)
  • Excel/CSV/PDF automation (openpyxl, csv) and sending email
  • Scheduling with cron, systemd timers or CI

Free resources

Practice

Automate something you do by hand every week (for example a report from a CSV emailed to you), make it a CLI with --dry-run, and schedule it with cron. See the Linux roadmap's cron topic.

DevOps and cloud with Python

Python runs a lot of infrastructure: AWS's official SDK boto3 automates EC2, S3, Lambda and every other service; Lambda functions are often written in Python; Ansible is written in Python; and CI pipelines run Python scripts for checks and releases. Read configuration from environment variables or files (os.environ, tomllib), never hard-code secrets.

With boto3, never put access keys in code: locally use a profile from aws configure or SSO, and in AWS use an IAM role, which boto3 picks up automatically. Use paginators for list calls and handle ClientError. In CI (GitHub Actions), set up Python, cache dependencies, run Ruff, mypy and pytest on every pull request, and package your app in a Docker image.

import boto3

# Credentials come from the environment, a profile or an IAM role, never from code.
s3 = boto3.client("s3")
paginator = s3.get_paginator("list_objects_v2")
total = 0
for page in paginator.paginate(Bucket="my-bucket", Prefix="logs/"):
    total += sum(obj["Size"] for obj in page.get("Contents", []))
print(f"{total / 1e6:.1f} MB under logs/")

What to learn

  • boto3 clients vs resources, paginators, waiters and ClientError
  • The AWS credential chain: profiles, SSO, IAM roles
  • Writing a Python AWS Lambda function
  • Python in CI: lint, type-check, test and build on every push
  • Containerising a Python app (slim base image, non-root user, pinned dependencies)

Free resources

Practice

Write a script that reports S3 buckets without default encryption or with public access, run it with a read-only IAM role, and add a GitHub Actions workflow that lints and tests it. Continue with the DevOps roadmap and AWS Lambda.

Portfolio and interview prep

Employers want proof you can build and finish things. Put two or three solid projects on GitHub from your chosen path, each with a README (what it does, how to run it, a screenshot), tests, type hints, a linter in CI and a clean commit history. One project that's deployed and used beats ten half-finished tutorials.

Python interviews usually include a coding round (data structures and algorithms in Python: know dict, set, collections.Counter, deque and heapq well), questions on the language itself (mutability, generators, decorators, the GIL, what is means) and, for experienced roles, design and a project discussion. Contributing a small fix to an open-source project is a great talking point.

from collections import Counter

def is_anagram(a: str, b: str) -> bool:
    return Counter(a) == Counter(b)

def two_sum(nums: list[int], target: int) -> list[int]:
    seen: dict[int, int] = {}
    for i, n in enumerate(nums):
        if target - n in seen:
            return [seen[target - n], i]
        seen[n] = i
    return []

What to learn

  • Two or three portfolio projects with READMEs, tests and CI
  • Python for coding interviews: built-in collections, heapq, bisect, slicing, sorting with keys
  • Explaining Python internals: mutability, references, generators, decorators, the GIL
  • Git and GitHub workflow: branches, pull requests, reviews
  • One open-source contribution (docs or a "good first issue")

Free resources

Practice

Solve the problems below in Python, then continue with the DSA roadmap (288 more problems). Polish your best project and share it with the pull request workflow from the Git roadmap.

Practice problems

Am I ready? Stage 4 quiz

What is the difference between np.array([1, 2, 3]) * 2 and [1, 2, 3] * 2?

  1. Both give [2, 4, 6]
  2. Both give [1, 2, 3, 1, 2, 3]
  3. The array doubles each number ([2 4 6]); the list repeats itself ([1, 2, 3, 1, 2, 3])
  4. The list version raises an error

NumPy operations are element-wise (vectorised). For lists, * means repetition.

With df = pd.DataFrame({"name": ["a", "b", "c"], "age": [25, 35, 40]}), what is df[df["age"] > 30]["name"].tolist()?

  1. ['b', 'c']
  2. ['a']
  3. [35, 40]
  4. [False, True, True]

df["age"] > 30 is a boolean mask; indexing with it keeps rows b and c, and then the name column is taken.

A Django page lists 100 books with their author's name and makes 101 database queries. What fixes it?

  1. Add an index on title
  2. Cache the template
  3. Use Book.objects.all() twice
  4. Book.objects.select_related("author")

That's the N+1 problem: one query for the books plus one per author. select_related fetches the authors in the same query with a JOIN.

Before scraping a website, what should you do first?

  1. Use many parallel requests so it finishes before you are blocked
  2. Look for an official API, read the terms and respect robots.txt and rate limits
  3. Hide your user agent
  4. Nothing; public pages can always be scraped

An API is more reliable and clearly allowed. Terms of service and robots.txt tell you what the owner permits; scraping politely (slowly, identified) avoids harming the site.

A Python script on an EC2 instance uses boto3. Where should its AWS credentials come from?

  1. Access keys written at the top of the script
  2. A credentials.txt committed next to the script
  3. An IAM role attached to the instance, which boto3 finds automatically
  4. The root user's keys in an environment variable

Instance roles give short-lived credentials that rotate automatically; boto3's credential chain picks them up with no code. Keys in code or files leak.

How to use this roadmap

  • Code every day. Type every example, then change it and see what breaks. An hour a day beats a whole Sunday once a week.
  • Practise on Exercism and LeetCode. The 74 practice problems are free. Exercism's Python track runs the tests in your browser or on your computer and offers free human mentoring; the LeetCode problems are all free (no Premium). Ticking a problem counts it here; it doesn't finish the topic.
  • Build one project through the stages. The practice tasks grow a log analyser from a script to a tested, typed, installable package, so you end up with something to show.
  • Choose one path in stage 4. Use the filter at the top (Web, Data & ML, Automation & DevOps) to dim the topics you don't need. Path topics are optional, so the percentage tracks the shared core plus the job-ready topic.
  • Track your progress. Ticking the first item in a topic marks it as in progress; ticking them all marks it done. Progress stays in this browser; use Export to move it to another device or Share progress to send a link.

Who this roadmap is for and how long it takes

It's for complete beginners and for developers coming from another language. The shared core (stages 1–3 plus the job-ready topic) is about 90 hours: roughly three months at an hour a day, or six weeks if you already program. A path in stage 4 adds 15–25 hours, and you'll keep learning it on the job. If you already know another language, skim stage 1, do its problems quickly and spend your time on stage 2, where Python differs most.

Frequently asked questions

Python 2 or Python 3?

Python 3, always. Python 2 reached its end of life on 1 January 2020 and gets no fixes, not even for security. You'll only meet it in very old systems; "Python" today means Python 3.

Which Python version should I install?

The latest stable release from python.org, which is Python 3.15 as of October 2026 (3.15.2). Each version gets about five years of support (two of bug fixes, then security fixes only); see the status of Python versions. Brand-new releases sometimes wait a few weeks for big libraries to publish wheels; if a package won't install on 3.15, use 3.14 for that project. Everything in this roadmap works on 3.12 and newer, except the few features marked with their version.

Which path should I choose first?

Choose by the job you want. Web if you want to build back ends and APIs (most junior Python jobs): start with FastAPI or Flask, then Django. Data & ML if you like numbers and questions: pandas first, then scikit-learn; SQL matters as much as Python here. Automation & DevOps if you work in IT, testing or operations: scripts that save your team time are the quickest way to show value. Not sure? Automation projects are useful in every job and teach the most Python per hour.

Do I need to learn data structures and algorithms?

For interviews at most product companies, yes: continue with the DSA roadmap in Python after stage 2. For scripting and data work, the built-in collections from this roadmap go a long way.

pip, uv or Poetry?

Learn venv + pip first, because everything else builds on them and every tutorial uses them. Then pick one tool per project for locking dependencies. uv is fast and does everything in one tool; Poetry is mature and widely used. Teams usually standardise on one.

Where to go next

Python pairs naturally with other roadmaps on this site: Backend for web developers, SQL & Databases for everyone (especially data people), DSA for interviews, Linux & Shell and Git & GitHub as daily tools, and DevOps and AWS for the automation path.

Python cheat sheet

Collectionslist [1, 2] · tuple (1, 2) · dict {"k": 1} · set {1, 2} · d.get(k, default) · sorted(xs, key=len, reverse=True)
Loopsfor i, x in enumerate(xs) · for a, b in zip(xs, ys) · for k, v in d.items() · [f(x) for x in xs if x]
Stringsf"{x:.2f} {n:,} {s!r} {x=}" · s.strip().split(",") · ", ".join(parts) · s[::-1]
Functionsdef f(a, b=None, *args, key=1, **kwargs) -> int: · lambda x: x * 2 · @functools.cache
Classes@dataclass(frozen=True) class P: x: int · @property · super().__init__() · __repr__
Errorstry: … except ValueError as e: … else: … finally: … · raise MyError("msg") from e
FilesPath("a") / "b.txt" · p.read_text(encoding="utf-8") · with open(p, "w", encoding="utf-8") as f:
Projectspython3 -m venv .venv · pip install -e . · pytest -x · ruff check --fix · ruff format · mypy src
Asyncasync def f(): await g() · asyncio.run(main()) · await asyncio.gather(a(), b()) · async with asyncio.TaskGroup() as tg: