Python Tutorial with Examples.
Python tutorial with runnable examples: practical Python for automation, data engineering, machine learning, AI, DevOps, backend development and testing.
Beginner
Start here — no prior experience needed
Introduction to Python
Learn what Python is, its history, and real-world use cases — a practical Python tutorial for beginners starting from scratch.
Setting Up Python
Install Python, create and activate a virtual environment, install and freeze packages with pip, and run a first script, with real command output.
Python Variables and Type System
See how Python variables work by running them: names as references, mutable vs immutable objects, dynamic typing, PEP 8 names and LEGB scope.
Python Data Types
Master Python's built-in data types — int, float, str, bool, None — and how to inspect and convert between them with real type conversion.
Python Operators
Run Python's arithmetic, comparison, identity, logical, membership, bitwise and walrus operators, plus operator overloading, and see each real result.
Python Strings
Slice, search, split, join and format Python strings with f-strings and format specs, plus escapes and raw strings, each example with real output.
Control Flow in Python
Run if/elif/else, match-case, for and while loops, for/else, break/continue and comprehensions in Python, each example shown with its real output.
Python Functions and Parameters
Define Python functions with positional, keyword, default, *args and **kwargs parameters, see the mutable-default trap, lambdas and return values run.
Python Data Structures
Use Python lists, tuples, dicts, sets and comprehensions through small runnable programs, plus a real timing of list vs set membership tests.
Python Collections
Work through list, dict, set and tuple, then deque, defaultdict, Counter and namedtuple from the collections module, each with its real printed output.
Python Modules and Packages
Build a real package step by step: import styles, the __name__ guard, __init__.py and __all__, relative imports, sys.path, venv and pyproject.toml.
Object-Oriented Programming in Python
Learn Python OOP — classes, objects, instances, inheritance, dunder methods, and encapsulation — with real-world examples.
Encapsulation and Name Mangling in Python
Learn how Python encapsulates state with the underscore convention and name mangling, and why neither one is real access control.
Polymorphism and Duck Typing in Python
See how Python's polymorphism works through duck typing, letting unrelated objects share behavior without a common base class or interface.
Abstraction with Abstract Base Classes in Python
Use Python's abc module to define abstract base classes that force subclasses to implement required methods before they can be instantiated.
Building a Python CLI Tool
Build a weather command-line tool with argparse, split CLI and API code, package it with pyproject.toml, and test it offline with unittest.mock.
Intermediate
For developers with core concepts down
Multiple Inheritance and MRO in Python
See how Python resolves the diamond problem with C3 linearization (MRO), and use mixins to combine behavior from unrelated classes safely.
Composition vs Inheritance in Python
Compare Python's has-a composition against is-a inheritance, and see how composition avoids the fragile base class problem.
Python Dataclasses
Use the @dataclass decorator to generate __init__, __repr__, and __eq__ automatically, plus frozen instances and post-init validation.
Error Handling in Python
Handle exceptions with try/except/else/finally, chain and re-raise them, define custom exceptions, use except* and logging, all with real tracebacks.
File I/O, pathlib, and JSON in Python
Read and write text files with open() and with, choose the right file mode, navigate paths with pathlib, and round-trip JSON and CSV, all with real output.
Python Decorators and Closures
Build closures, then decorators: functools.wraps, decorator factories, stacking order, stateful class decorators and lru_cache, each with real output.
Python Generators
Write generators with yield, see their lazy execution step by step, then build pipelines with yield from, send(), generator expressions and itertools.
Python Context Managers
See exactly when __enter__ and __exit__ run, then build context managers with classes, @contextmanager, suppress and ExitStack, with real output.
Python Concurrency
Run threads, processes and concurrent.futures side by side: see the GIL in real timings, a race condition and its Lock fix, queues and executors.
Testing Python Code
Write and run pytest tests: assertions, exceptions, fixtures, parametrize, mocks, coverage, async tests and unittest, with real pytest output for each.
Python Security
Run real attacks against local Python code and fix them: SQL injection, shell injection, path traversal, weak tokens and password hashes.
Python Interview Prep
30 Python interview questions with concise answers and runnable code: the GIL, mutable defaults, decorators, MRO, closures, copying and more.
Advanced
Production-grade patterns for experienced engineers
Async Python with asyncio
Learn asyncio by running it: coroutines, gather, create_task, TaskGroup, async with, timeouts and aiohttp against a local server, with real output shown.
Python Type Hints and Static Typing
Annotate Python code and run mypy on it: unions, narrowing, generics, Protocol, TypedDict and --strict, with the real errors each one catches.
Python Memory Management
Watch CPython free objects: reference counts, cycles and gc.collect, weakref caches, __slots__ savings and tracemalloc profiling, with measured output.
Python Performance
Measure before optimising: timeit, cProfile and line_profiler on real code, then lru_cache, set lookups, str.join, NumPy and __slots__, timed.
Python Design Patterns
Run singleton, factory, observer, strategy, decorator and command patterns in idiomatic Python, and see where functions and modules replace classes.
Python Metaclasses
Understand Python's type system, metaclasses, __new__ vs __init__, custom metaclasses, __init_subclass__, and class decorators with real executed output.