Library
Python Step by Step: Foundation to Advanced
A clear path to learn Python, from your first program to advanced topics, with a real-world example for every topic.
The whole path on one page
| Phase | Topics (in order) | Rough time |
|---|---|---|
| 1. Foundation | Setup → variables and memory → numbers and operators → strings → input → if/elif/match → loops → list/tuple/set/dict → functions → modules → exceptions → files/JSON/CSV → venv and pip | Weeks 1–2 |
| 2. Intermediate | Comprehensions → lambda/map/filter → closures and decorators → OOP (class, inheritance, polymorphism, ABC) → iterators and generators → context managers → dataclasses and enums → regex → stdlib tour → HTTP APIs → testing → type hints → Git | Weeks 3–4 |
| 3. Advanced | Concurrency (threads, processes, asyncio) → data model and descriptors → advanced typing → pattern matching → exception groups → metaprogramming → internals and profiling → packaging (uv, ruff) → modern 3.10–3.15 features | Weeks 5–6 |
| 4. DSA | Big-O → arrays/strings → hashing → prefix sums → two pointers/sliding window → stack/queue → sorting → binary search → linked list → recursion → trees → heaps → greedy → intervals → tries → graphs → topo sort/union-find → shortest paths → DP → bits | Weeks 7–8 |
| 5. Specialization | Pick one: Web backend, Data analytics, ML/AI, Automation | Weeks 9–10 |
Phase 1: Foundation
| # | Topic | Subtopics | Real-world example |
|---|---|---|---|
| 1 | Setup and first program | Install 3.13+, VS Code, REPL vs script, print() |
Print a welcome banner |
| 2 | Variables and memory | Names point to objects, id(), mutable vs immutable, reassignment, constants |
Two variables sharing one cart |
| 3 | Data types and type casting | int, float, bool, str, None, int()/float()/str() |
Convert a typed price "49.5" to a float |
| 4 | Operators | Arithmetic, //, %, **, comparison, logical, precedence |
Split a restaurant bill |
| 5 | Strings | Indexing, slicing, methods (split, join, strip, replace), f-strings |
Format a receipt line |
| 6 | Input/output | input(), casting the input |
Ask for an age and check it |
| 7 | Conditionals | if/elif/else, nesting, match-case (3.10+) |
ATM menu |
| 8 | Loops | while, for, range, break/continue/pass, loop else |
Allow 3 login attempts |
| 9 | Collections | list, tuple, set, dict, their methods, nesting | Shopping cart |
| 10 | Functions | def, return, default/keyword args, *args/**kwargs, scope, global, docstrings |
Discount calculator |
| 11 | Modules | import, math, random, packages, __name__ == "__main__" |
Random OTP generator |
| 12 | Exceptions | try/except/else/finally, raise, custom exceptions |
Safe number input |
| 13 | Files, JSON, CSV, venv/pip | open + with, modes r/w/a, json, csv, pathlib, python -m venv, pip |
Save a to-do list |
Tips
- Recursion (T#31–33) also appears in this part of the playlist. You can watch it now or in Phase 4.
Example snippets
Variable storage (T#12): shopping cart
cart = ["apple"]
backup = cart # same object, NOT a copy
backup.append("milk")
print(cart) # ['apple', 'milk']
print(cart is backup) # True -> use cart.copy() for a real copy
Collections (T#8–11): shopping cart with a dict
prices = {"apple": 30, "milk": 55, "bread": 40}
cart = ["apple", "milk", "apple"]
total = sum(prices[item] for item in cart)
print(f"Items: {len(cart)}, Total: ₹{total}") # Items: 3, Total: ₹115
Conditionals with match (T#23): order status
status = "shipped"
match status:
case "placed": print("We got your order")
case "shipped": print("On the way!")
case "delivered" | "picked_up": print("Enjoy!")
case _: print("Unknown status")
Functions (T#15, T#29): discount calculator
def final_price(price, discount=10, *, coupon=None):
if coupon == "FEST50":
discount += 50
return round(price * (1 - discount / 100), 2)
print(final_price(1000)) # 900.0
print(final_price(1000, coupon="FEST50")) # 400.0
Exceptions (T#53): safe input
while True:
try:
qty = int(input("Quantity: "))
break
except ValueError:
print("Please type a whole number.")
Files + JSON: to-do list that remembers
import json
from pathlib import Path
file = Path("todos.json")
todos = json.loads(file.read_text()) if file.exists() else []
todos.append("Pay electricity bill")
file.write_text(json.dumps(todos, indent=2))
Exam checkpoint: Phase 1 matches PCEP-30-03: 35 questions, 50 minutes, 70% to pass. Its sections are fundamentals, control flow, collections (the largest part), functions and exceptions, and files and modules.
Phase 2: Intermediate
| # | Topic | Subtopics | Real-world example |
|---|---|---|---|
| 14 | Comprehensions | list/dict/set comprehensions, nested, generator expressions | Filter in-stock products |
| 15 | Functional tools | Higher-order functions, lambda, map, filter, reduce, sorted(key=) |
Sort products by price |
| 16 | Closures and decorators | Inner functions, nonlocal, @decorator, functools.wraps, decorators with arguments |
Timing/logging decorator |
| 17 | OOP basics | class, object, self, __init__, __new__, instance/class/static methods, @property |
Bank account |
| 18 | Inheritance | Single, multilevel and multiple inheritance, MRO, super(), overriding |
Savings account extends account |
| 19 | Polymorphism and dunders | Duck typing, __str__, __add__, __eq__, operator overloading |
Add two Money objects |
| 20 | Abstract classes | abc.ABC, @abstractmethod |
PaymentMethod → UPI, Card |
| 21 | Iterators and generators | __iter__/__next__, yield, lazy processing |
Read a 5 GB log line by line |
| 22 | Context managers | with, __enter__/__exit__, contextlib.contextmanager |
Auto-close a DB connection |
| 23 | Dataclasses and enums | @dataclass, frozen, field(), Enum, StrEnum |
Product record, order-status enum |
| 24 | Regular expressions | re.search/findall/sub, groups, named groups |
Log parser |
| 25 | Standard library tour | datetime, pathlib, os, sys, argparse, logging, collections, itertools, functools |
CLI that renames photos by date |
| 26 | HTTP APIs | pip install requests, GET/POST, JSON, timeouts, status codes |
Weather API |
| 27 | Testing and debugging | assert, pytest, pytest.raises, debugger, breakpoint() |
Test the discount function |
| 28 | Type hints | list[str], `int | ⚠️ |
Typed final_price() |
| 29 | Git and GitHub | commit, branch, pull request, README | Push projects to GitHub |
Example snippets
Comprehension: in-stock products
products = [{"name": "Pen", "stock": 5}, {"name": "Ink", "stock": 0}]
available = [p["name"] for p in products if p["stock"] > 0] # ['Pen']
Decorator (T#39): time any function
import time, functools
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
print(f"{func.__name__} took {time.perf_counter() - start:.3f}s")
return result
return wrapper
@timer
def generate_report():
time.sleep(0.5)
OOP (T#42–52): bank account
from abc import ABC, abstractmethod
class Account(ABC):
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("Amount must be positive")
self._balance += amount
@abstractmethod
def monthly_fee(self): ...
class Savings(Account):
def monthly_fee(self):
return 0 if self._balance >= 10_000 else 50
def __str__(self):
return f"{self.owner}: ₹{self._balance}"
acc = Savings("Asha", 5000)
acc.deposit(6000)
print(acc, acc.monthly_fee()) # Asha: ₹11000 0
Generator: huge log file without running out of memory
def error_lines(path):
with open(path, encoding="utf-8") as f:
for line in f: # reads one line at a time
if "ERROR" in line:
yield line.strip()
for line in error_lines("server.log"):
print(line)
Regex: log parser
import re
line = "2026-11-26 10:15:02 ERROR [payment] Card declined for order 4512"
pattern = r"(?P<date>\S+) (?P<time>\S+) (?P<level>ERROR|WARN|INFO) \[(?P<svc>\w+)\] (?P<msg>.*)"
m = re.match(pattern, line)
print(m["level"], m["svc"], m["msg"]) # ERROR payment Card declined for order 4512
HTTP API: weather (Open-Meteo, no key needed)
import requests
r = requests.get(
"https://api.open-meteo.com/v1/forecast",
params={"latitude": 17.38, "longitude": 78.48, "current": "temperature_2m"},
timeout=10,
)
r.raise_for_status()
print("Hyderabad now:", r.json()["current"]["temperature_2m"], "°C")
pytest: test your discount function
# test_price.py -> run with: pytest
from shop import final_price
import pytest
def test_default_discount():
assert final_price(1000) == 900.0
def test_bad_price():
with pytest.raises(TypeError):
final_price("abc")
Exam checkpoint: Phase 2 matches PCAP-31-04: 42 questions, 65 minutes, 72% to pass. OOP is the biggest part of the exam. It also covers closures, match, pathlib, unit tests, Git/CI and validating AI-generated code.
Phase 3: Advanced
| # | Topic | Subtopics | Real-world example |
|---|---|---|---|
| 30 | Threads | threading, Thread, join, Lock, queue, the GIL |
Download several reports at once |
| 31 | Processes and executors | multiprocessing, concurrent.futures (Thread/ProcessPoolExecutor) |
Resize 1,000 images on all CPU cores |
| 32 | asyncio | async/await, asyncio.run, TaskGroup, asyncio.timeout() |
Parallel downloader |
| 33 | Data model deep dive | Dunder protocols, __repr__, __hash__, __getitem__, __call__, __slots__ |
Custom Cart that works with len() and for |
| 34 | Descriptors and properties | __get__/__set__, __set_name__, __getattr__ |
A reusable "positive number" field |
| 35 | Advanced typing | Protocol, generics def f[T](), type X = ..., TypedDict, ParamSpec, @override |
Typed repository class |
| 36 | Pattern matching (deep) | Sequence, mapping and class patterns, guards | Route JSON webhook events |
| 37 | Advanced exceptions | raise ... from, ExceptionGroup, except*, add_note() |
Collect errors from many parallel tasks |
| 38 | Metaprogramming | type(), __init_subclass__, class decorators, metaclasses |
Plugin auto-registration |
| 39 | Internals and performance | Reference counting, gc, dis, timeit, cProfile, profiling (3.15), caching |
Find the slow function in a script |
| 40 | Packaging and tooling | pyproject.toml, uv, Ruff, mypy/pyright, pre-commit, logging config, CLI entry points |
Publish your own CLI tool |
asyncio parallel downloader: 3 "downloads" in about 1 second instead of 3
import asyncio
async def download(url):
await asyncio.sleep(1) # pretend network wait
return f"{url} done"
async def main():
urls = ["a.com/file1", "b.com/file2", "c.com/file3"]
async with asyncio.TaskGroup() as tg:
tasks = [tg.create_task(download(u)) for u in urls]
print([t.result() for t in tasks])
asyncio.run(main())
Swap asyncio.sleep for an async HTTP client such as httpx.AsyncClient to fetch real pages. TaskGroup (3.11) is recommended over bare gather() for new code.
Which concurrency tool to use
| Job type | Use | Why |
|---|---|---|
| Many network/file waits | asyncio or threads |
Waiting does not need the CPU |
| Heavy CPU math | multiprocessing / ProcessPoolExecutor |
Gets around the GIL on the normal build |
| CPU work with threads | Free-threaded build python3.14t |
Officially supported in 3.14, but not the default |
Modern Python 3.10 to 3.15: what to actually use
| Version (status, Nov 2026) | Learn and use daily | Know it exists |
|---|---|---|
| 3.10 (EOL 1 Oct 2026) | match/case, X | Y types, zip(strict=True), better error messages |
ParamSpec, dataclass(slots=True) |
| 3.11 (security only) | Much faster, except* / ExceptionGroup, TaskGroup, tomllib, Self |
Fine-grained tracebacks |
| 3.12 (security only) | def f[T]() generics, type alias statement, f-strings that can reuse quotes, itertools.batched, @override |
distutils removed, comprehension inlining |
| 3.13 (security only) | New colourful REPL | Experimental no-GIL build and JIT, 19 old modules removed |
| 3.14 (bugfix) | t-strings t"..." for safe templates, annotations no longer need quotes, except A, B: without parentheses |
Free-threading officially supported, concurrent.interpreters, pdb -p PID |
| 3.15 (current, 9 Oct 2026) | lazy import, frozendict, [*L for L in lists], UTF-8 by default |
profiling package (Tachyon sampler), sentinel, upgraded JIT |
# A few modern idioms in one place (3.12+; lazy needs 3.15)
type UserId = int # 3.12 type alias
def first[T](items: list[T]) -> T | None:
return items[0] if items else None # 3.12 generics + 3.10 union
if (n := len("hello")) > 3: # walrus (3.8)
print(f"{n=}") # prints n=5
Phase 4: DSA
| Order | DSA topic | Python tool | Real-world example |
|---|---|---|---|
| 1 | Big-O, cost of built-ins | timeit |
Why x in set beats x in list |
| 2 | Arrays and strings | list, str, join, zip(*grid) |
Sales grid totals |
| 3 | Hashing | dict, set, Counter, defaultdict |
Count the most-sold products |
| 4 | Prefix sums / difference arrays | plain lists | Range totals, bulk bookings |
| 5 | Two pointers / sliding window | lists, deque |
Best 7-day sales streak |
| 6 | Stack and queue (incl. monotonic) | list, collections.deque |
Undo button, days-until-warmer |
| 7 | Sorting | sorted(key=), stability |
Rank orders by priority, then distance |
| 8 | Binary search | bisect |
Next bus at or after a time |
| 9 | Linked list | custom class | Playlist, browser history |
| 10 | Recursion and backtracking | functions (T#31–33) | Folder size, delivery-stop orders |
| 11 | Trees and BST | custom class | Org chart, folder tree |
| 12 | Heaps | heapq, a min-heap |
Top-k trending posts |
| 13 | Greedy | sorting + a proof (or a counterexample) | Fewest notes, most meetings |
| 14 | Intervals | sort + sweep | Merged bookings, rooms needed |
| 15 | Tries | nested dicts | Contact autocomplete |
| 16 | Graphs | adjacency dict, BFS/DFS | Delivery zones, reachability |
| 17 | Topological sort / union-find | deque, parent pointers |
Prerequisite order, friend circles |
| 18 | Shortest paths | Dijkstra with heapq |
Cheapest metro route |
| 19 | Dynamic programming | functools.cache, tables |
Coin change, knapsack, LCS |
| 20 | Bit manipulation | & | ^ ~ << >> |
Permission flags, unpaired ID |
Use deque.popleft() instead of list.pop(0). In a loop, pop(0) makes the whole job quadratic.
from collections import deque
def bfs(graph, start): # shortest hops, e.g. friend suggestions
seen, q = {start}, deque([start])
while q:
node = q.popleft()
for nxt in graph[node]:
if nxt not in seen:
seen.add(nxt); q.append(nxt)
return seen
Databases (taught back in Part 12, revised here alongside DSA)
- SQL basics: SELECT, JOIN, GROUP BY.
sqlite3, with parameterized queries only.
Going further — not covered by this course, learn on the job or in the Web backend track: PostgreSQL, SQLAlchemy 2.0 (select() + Session; the old Query API is legacy), Alembic migrations.
import sqlite3
with sqlite3.connect("shop.db") as db:
db.execute("CREATE TABLE IF NOT EXISTS orders (id INTEGER PRIMARY KEY, item TEXT, qty INT)")
db.execute("INSERT INTO orders (item, qty) VALUES (?, ?)", ("milk", 2)) # ? stops SQL injection
print(db.execute("SELECT item, SUM(qty) FROM orders GROUP BY item").fetchall())
Phase 5: Specializations (pick one)
| Track | Learn these | Core subtopics | Real-world starter |
|---|---|---|---|
| Web backend | FastAPI, Django, Flask, Pydantic | REST, routing, validation, async, ORM, auth (JWT), Docker | To-do REST API |
| Data analytics | pandas, NumPy, Polars, Streamlit | Cleaning, groupby, merge, charts (Matplotlib/Seaborn), SQL, Jupyter | Sales dashboard |
| ML / AI | scikit-learn, PyTorch, Hugging Face + LLM APIs | Train/test split, metrics, pipelines, RAG, agents, evaluation | Churn predictor, PDF chatbot |
| Automation / scraping | Requests, BeautifulSoup, Playwright/Selenium, openpyxl | Files, Excel, scraping, scheduling, CLI | Daily price tracker |
Day-by-day timeline (about 1 hour a day)
Each stage is two weeks, so the whole course is ten weeks end to end.
| Days | Learn | Build / check |
|---|---|---|
| 1–2 | Setup, first code, numbers, strings | Tip calculator |
| 3–5 | Collections, variable storage, types, operators, input, swap | Shopping-cart total |
| 6–7 | if/elif/match, loops | Number-guessing game |
| 8–10 | Functions, args, scope, modules, array |
Password generator |
| 11–12 | Recursion, exceptions, files/JSON/CSV | P1: To-do CLI with JSON storage |
| 13–14 | venv, pip, f-strings, comprehensions, Git basics | Push P1 to GitHub; PCEP practice test |
| 15–16 | Lambda, map/filter/reduce, closures, decorators | Timer decorator |
| 17–19 | OOP: class, __init__, __new__, method types |
Bank-account class |
| 20–21 | Inheritance, MRO, polymorphism, overloading, ABC | Payment-method hierarchy |
| 22–24 | Iterators, generators, context managers, dataclasses, enums | Lazy log reader |
| 25–26 | Regex, stdlib tour, requests + APIs |
P2: Weather CLI or log analyzer |
| 27–28 | pytest, type hints, debugging | Add tests to P1/P2; PCAP practice test |
| 29–31 | Threads, processes, executors | Parallel image resizer |
| 32–35 | asyncio, TaskGroup | Async downloader |
| 36–38 | Data model, descriptors, advanced typing, pattern matching | Typed Cart with dunders |
| 39–42 | Modern 3.12–3.15 features, uv, Ruff, packaging, logging | P3: Package and publish a CLI tool |
| 43–49 | DSA: Big-O, hashing, two pointers, stack/queue, sorting, binary search | 2 LeetCode-easy problems a day |
| 50–56 | DSA: linked list, trees, heaps, graphs, DP + SQL/sqlite3 revision (Part 12) | P4: Expense tracker with SQLite |
| 57–70 | Specialization track + capstone | P5: Capstone (see below) |
If you can only study on weekends, double each row. A slower pace is fine as long as you keep building each project.
Projects by level
| Level | Project | Skills proven |
|---|---|---|
| ⭐ Beginner | Number guessing game, Rock-Paper-Scissors, unit converter | Loops, conditionals, input |
| ⭐ Beginner | Task Tracker CLI / Expense Tracker (JSON file) | Collections, functions, files, exceptions |
| ⭐⭐ Beginner+ | Weather API CLI, GitHub User Activity CLI | requests, JSON, argparse |
| ⭐⭐ Beginner+ | Job-listings scraper, Titanic/Netflix data cleaning, SQLite queries | BeautifulSoup, pandas, SQL |
| ⭐⭐⭐ Intermediate | Todo/Blog REST API (FastAPI + SQLAlchemy + pytest) | OOP, DB, testing, typing |
| ⭐⭐⭐ Intermediate | URL shortener, Markdown notes app, Discord bot, Streamlit dashboard, LLM-API chatbot | Web, async, APIs |
| ⭐⭐⭐⭐ Advanced | Caching proxy, image-processing service, real-time leaderboard | Concurrency, caching, Redis |
| ⭐⭐⭐⭐ Advanced | Movie reservation system, scalable e-commerce (microservices), RAG app over your PDFs | Transactions, Docker, CI, cloud, LLMs |
Make every project "portfolio-ready"
- A README with setup steps
- At least 5 pytest tests
- Type hints, and Ruff passing
- A clean Git history
- For P3 and later, a deployed link or Docker file
Interview checklist
| ✔ | Topic | Be ready to explain / code | Phase |
|---|---|---|---|
| ☐ | Mutable vs immutable; is vs == |
Why changing backup also changed cart (T#12) |
1 |
| ☐ | Mutable default argument trap | def add(x, items=[]) shares one list across calls → use None |
1 |
| ☐ | Argument passing | "Pass by object reference" | 1 |
| ☐ | Scope (LEGB), global, nonlocal |
Closure counter | 1–2 |
| ☐ | Built-in data structures | When to use list vs tuple vs set vs dict | 1 |
| ☐ | Comprehensions | Dict comprehension from two lists | 2 |
| ☐ | *args / **kwargs, lambda vs def |
Write a flexible logger | 2 |
| ☐ | Generators and yield |
Why they save memory | 2 |
| ☐ | Decorators | Write @timer with functools.wraps, plus one with arguments |
2 |
| ☐ | OOP | Dunder methods, @property, class vs static method, MRO, ABC vs Protocol, dataclasses |
2–3 |
| ☐ | Shallow vs deep copy | copy.copy vs copy.deepcopy on nested lists |
2 |
| ☐ | Memory and GC | Reference counting + cyclic garbage collector | 3 |
| ☐ | GIL and concurrency | Threads (I/O) vs processes (CPU) vs asyncio, plus the 2026 update: free-threaded 3.14t is officially supported but optional | 3 |
| ☐ | Context managers and exceptions | Write one with contextlib; finally vs else |
2–3 |
| ☐ | Type hints | list[int], X | None, generics |
2–3 |
| ☐ | Coding: LRU cache, read and process a text file | OrderedDict or functools.lru_cache |
4 |
| ☐ | DSA patterns | Two pointers, sliding window, BFS/DFS, heaps (top-k), binary search | 4 |
| ☐ | Track questions | Backend: REST, ORM, async, Pydantic. Data: pandas vs NumPy, DataFrame merge, SQL joins. AI: RAG, evaluation | 5 |
The #1 trap, in code
def add_item(item, cart=[]): # BAD: one list shared by every call
cart.append(item); return cart
add_item("pen"); print(add_item("ink")) # ['pen', 'ink'] surprise!
def add_item(item, cart=None): # GOOD
cart = [] if cart is None else cart
cart.append(item); return cart