Learn Python
From Zero to Production
A structured path through every stage of Python — from running your first script to building real applications, working with data, and shipping to the web. Follow in order or jump to where you are.
Getting Started
FoundationsBefore writing real code you need Python installed and a mental model of what the language is. This stage takes about a weekend.
- Interpreted vs compiled languages
- Why Python: readable syntax, huge ecosystem
- Where Python is used: web, data, AI, scripting
- CPython, PyPy — what runs your code
- Install Python 3 on Windows / macOS / Linux
- The Python REPL — interactive exploration
- VS Code setup: Python extension, linter, formatter
- Running your first
.pyfile
- Why isolate dependencies per project
python -m venv envand activating it- pip: installing and listing packages
requirements.txt— freeze and restore
Core Language
FoundationsThe building blocks every Python program is made of. Master these before moving on — everything else builds on them.
int,float,complexstr— string creation and immutabilitybool—True/Falseand truthiness- Dynamic typing and
type() - Type casting:
int(),str(),float()
- Arithmetic:
+-*///%** - Comparison:
==!=><>=<= - Logical:
andornot - Bitwise:
&|^~<<>> - Identity:
is/is not— vs== - Membership:
in/not in
if/elif/else- Ternary expression:
x if cond else y forloops andrange()whileloopsbreak,continue,passfor … elseandwhile … else
- Indexing and slicing:
s[1:5:2] - f-strings and
format() - Common methods:
.split(),.join(),.strip(),.replace() - Multi-line strings and raw strings
- String immutability
Data Structures
FoundationsPython's built-in data structures are some of its greatest strengths. Understanding when to use each one is fundamental to writing clean code.
- Creating, indexing, slicing
.append(),.extend(),.insert(),.pop(),.remove()- Sorting:
.sort()vssorted() - List comprehensions:
[x*2 for x in nums if x>0] - Nested lists and 2D arrays
- Tuples — immutable sequences, packing/unpacking
- When to use tuple over list
- Sets — unique unordered elements
- Set operations: union, intersection, difference
- Frozensets
- Key-value pairs, hashing
.get(),.keys(),.values(),.items()- Dict comprehensions
- Nested dictionaries
defaultdict,Counter,OrderedDict
collectionsmodule:deque,namedtuple- Stack and queue patterns using lists
- Choosing the right structure: time complexity
- Memory efficiency considerations
Functions and Modules
Core SkillsFunctions are Python's primary unit of code reuse. This stage also covers how Python organises code across files and packages.
defandreturn- Positional, keyword, default arguments
*argsand**kwargs- Docstrings and
help() - Type hints:
def add(a: int, b: int) -> int
- LEGB rule: Local, Enclosing, Global, Built-in
globalandnonlocalkeywords- Closures and factory functions
- Why closures matter for callbacks and decorators
- Anonymous functions:
lambda x: x*2 map(),filter(),reduce()- Functions as first-class objects
- Passing functions as arguments
import,from … import,as__name__ == "__main__"guard- Creating your own module
- Package structure:
__init__.py - Standard library highlights:
os,sys,math,datetime,random
Object-Oriented Programming
Core SkillsOOP organises code around objects — bundles of data and behaviour. Python's OOP is flexible and less ceremonial than Java or C++.
classkeyword,__init__- Instance vs class attributes
self— what it is and why- Instance methods, class methods, static methods
__repr__and__str__
- Encapsulation:
_privateand__name_mangling - Inheritance:
class Dog(Animal) - Polymorphism: duck typing and method overriding
- Abstraction:
abcmodule,@abstractmethod super()and MRO (Method Resolution Order)
__len__,__getitem__,__setitem__- Operator overloading:
__add__,__eq__ - Context managers:
__enter__/__exit__ - Making your class iterable:
__iter__/__next__
@dataclass— auto-generate__init__,__repr__field(),frozen=TrueEnum— named constants- When to use dataclass vs namedtuple vs dict
File Handling, Errors and Testing
Core SkillsReal programs read and write files, fail gracefully, and have tests to prove they work correctly. These three skills together make your code production-ready.
open()modes:r,w,a,rb- Context manager:
with open(...) as f - Reading:
.read(),.readline(),.readlines() - Writing and appending
- Working with
pathlib.Path - CSV:
csvmodule and DictReader/DictWriter - JSON:
json.load()/json.dump()
- Files vs databases — when each makes sense
- SQLite with
sqlite3 - ORMs: intro to SQLAlchemy
- Pickle and shelve for Python objects
- Environment variables and
.envfiles
try/except/else/finally- Built-in exceptions:
ValueError,TypeError,KeyError,FileNotFoundError - Raising exceptions:
raise - Custom exception classes
- Exception chaining:
raise X from Y
- Why test? — catching regressions early
unittest— standard library test frameworkpytest— simpler syntax, fixtures, parametrize- Writing assertions:
assertkeyword - Mocking with
unittest.mock - Test-driven development (TDD) basics
Applied Python: Data and NumPy
Applied PythonPython dominates data work. NumPy is the foundation for nearly every data-science and machine-learning library in the ecosystem.
- Why NumPy: vectorised operations, no loops
np.array(),np.zeros(),np.ones(),np.arange()- Shape, dtype, ndim, reshape
- Indexing, slicing, boolean masking
- Broadcasting rules
- Universal functions (ufuncs)
- Stacking and splitting arrays
SeriesandDataFrame- Reading:
pd.read_csv(),read_json(),read_excel() - Selecting data:
.loc,.iloc - Filtering, groupby, merge, pivot
- Handling missing data:
.dropna(),.fillna() - Apply and vectorised string operations
- Matplotlib: line, bar, scatter, histogram
- Subplots and figure layout
- Seaborn for statistical plots
- Plotly for interactive charts
- Saving figures to PNG/SVG
re.match(),re.search(),re.findall()- Character classes, quantifiers, groups
- Named groups:
(?P<name>...) - Substitution:
re.sub() - Compiling patterns for performance
Applied Python: Computer Vision
Applied PythonOne of Python's most exciting application areas. These tutorials walk you through building a face recognition system from scratch — a real project that touches NumPy, OpenCV, and dlib together.
- Installing:
pip install opencv-python - Reading, displaying, and saving images
- Colour spaces: BGR, RGB, grayscale, HSV
- Drawing on images: rectangles, text, circles
- Resizing, cropping, flipping
- Thresholding and edge detection (Canny)
cv2.VideoCapture(0)- Frame-by-frame processing loop
- Displaying real-time output
- Recording video to file
- Performance: frame rate and resolution
- What dlib is and when to use it over OpenCV
- HOG-based face detector
- 68-point facial landmark predictor
- Face alignment for recognition accuracy
- CNN face detector (more accurate, GPU optional)
face_recognitionlibrary: encoding faces- Comparing encodings: Euclidean distance
- Building a known-faces database
- Real-time identification from webcam
- Full project walkthrough (4 phases)
face_recognition.load_image_file()face_encodings()— 128-d vector per facecompare_faces()andface_distance()- Batch processing a directory of images
- Tolerance tuning for accuracy vs false positives
Advanced Language Features
AdvancedThese are the features that separate good Python from excellent Python — the tools experienced developers reach for every day.
- Iterator protocol:
__iter__/__next__ yield— turning a function into a generator- Generator expressions:
(x*2 for x in range(n)) itertools:chain,islice,product,groupby- Lazy evaluation and memory efficiency
yield from— delegating to sub-generators
- What a decorator is: a function wrapping a function
- Writing your first decorator
functools.wraps— preserve metadata- Decorators with arguments
- Class-based decorators
- Built-in:
@property,@staticmethod,@classmethod,@cache
withstatement — resource management- Writing one with
__enter__/__exit__ contextlib.contextmanagerwithyield- Nested context managers
- Use cases: files, locks, database transactions
- The GIL — what it is and what it limits
- Threading:
threading.Thread, locks, race conditions - Multiprocessing: bypassing the GIL with
multiprocessing - Async/await:
asyncio, coroutines, event loop concurrent.futures:ThreadPoolExecutor,ProcessPoolExecutor- When to use which: I/O-bound vs CPU-bound
- Full type hint syntax:
Union,Optional,TypeVar typing.Protocol— structural subtyping- Generic classes:
list[int],dict[str, float] - Running mypy for static analysis
typing.overloadfor function signatures
- Metaclasses and
type() __slots__for memory optimisation- Descriptors:
__get__,__set__,__delete__ getattr/setattr/hasattr/delattrinspectmodule — introspection at runtime
Production Python and Web
AdvancedThe final stage — packaging your work, shipping to the web, and building on the ecosystem of frameworks that make Python a professional-grade tool.
- Flask: routes, templates (Jinja2), request/response
- FastAPI: async routes, auto docs, Pydantic validation
- Django: ORM, admin, migrations, auth (full-stack)
- Choosing: Flask for minimal APIs, FastAPI for performance, Django for full apps
- REST API design fundamentals
requests: GET, POST, headers, auth, params- Handling responses: status codes, JSON parsing
httpxfor async HTTP- API keys and OAuth basics
- Rate limiting and retry logic
- Web scraping with BeautifulSoup and Playwright
pyproject.toml— modern project config- Building with
buildand publishing to PyPI - Semantic versioning
- CLI tools:
argparse,click,typer - Logging:
loggingmodule, handlers, formatters
- Docker: containerising a Python app
- WSGI vs ASGI: Gunicorn, Uvicorn
- Render, Railway, Fly.io — free-tier hosting
- Environment variables and secrets management
- Basic CI/CD: GitHub Actions to auto-deploy
- scikit-learn: classification, regression, clustering
- Train/test split, cross-validation, metrics
- TensorFlow and PyTorch — when you need deep learning
- Jupyter notebooks for exploration
- Hugging Face — using pre-trained models
Want everything in one place? The full notes cover Stages 1–6 end to end with examples and exercises.
