Python

The most popular first language: simple, powerful, versatile

Learn to write Python programs from zero: from variables and conditions all the way to functions, classes and working with files. In every lesson you run the code right in your browser and see the result. By the end of the course you will be able to build a small but real project on your own.

  • Beginner
  • Intermediate
  • Advanced
  • University
lessons
66
modules
16
tests
22
hours of lessons
23.3

Course content

16 modules, 66 lessons. Each module has its own level, and the lessons follow in order.

  1. Python basics

    Beginner3 lessons · 40 min

    Write your first program and get to know variables, data types, arithmetic and strings.

    1. 1What is Python? Your first programFind out what Python is and where it is used, and write your first program with print().10 min
    2. 2Variables, data types and arithmeticStore values in variables, meet the basic data types, do calculations and convert one type into another.15 min
    3. 3Strings and f-stringsLearn to work with text: joining, indexes, slices, handy methods and templates with f-strings.15 min
  2. Conditions and loops

    Beginner2 lessons · 31 min

    Teach your program to make decisions and to repeat work.

    1. 4Conditions: if, elif, elseTeach your program to make decisions: comparison operators, if/elif/else and the logical and, or, not.15 min
    2. 5Loops: for and whileLearn to repeat work: for with range(), while, and the loop controls break and continue.16 min
  3. Data structures

    Intermediate4 lessons · 67 min

    Store and process many values with lists, tuples, sets and dictionaries.

    1. 6ListsKeep many values in one list: access items, add and remove them, sort them and loop over the list.17 min
    2. 7Tuples and setsLearn to use tuples for data that should not change and sets for collections without duplicates.14 min
    3. 8DictionariesStore data as key: value pairs: create a dictionary, change it, loop over it and use it for counting.16 min
    4. 9Names, references and mutabilityIn Python a variable is not a box but a name bound to an object: `id()`, `is` and `==`, mutable and immutable types, aliasing traps, shallow and deep copies with the `copy` module, objects passed to functions and the mutable default argument trap.20 min
  4. Functions and modules

    Intermediate4 lessons · 69 min

    Split code into reusable functions, use the standard library and handle errors gracefully.

    1. 10FunctionsWrite your own functions: parameters, returning values with return, default values and variable scope.17 min
    2. 11Recursion: functions that call themselvesHow a function solves a task by calling itself on a smaller version of it: the base case and the recursive step, the call stack and `RecursionError`, factorial, Fibonacci, digit sums, recursive binary search, nested lists and folder trees, and when a loop or `lru_cache` is the better choice.22 min
    3. 12Modules and the standard libraryUse ready-made tools: import, the math, random and datetime modules and other handy parts of the standard library.15 min
    4. 13Handling errors: try and exceptStop your program from crashing: recognise exceptions, catch them with try/except/else/finally and raise your own.15 min
  5. Advanced Python

    Advanced3 lessons · 54 min

    Write concise code, build classes, work with files and combine everything in a project.

    1. 14List and dictionary comprehensionsBuild lists, dictionaries and sets in one line: comprehensions, filter conditions and generator expressions.14 min
    2. 15Object-oriented programming: classes and objectsBundle data and behaviour together: classes, objects, __init__, methods, self and inheritance.20 min
    3. 16Files and a mini project: grade calculatorLearn to write to and read from files, then combine everything from the course in a grade calculator project.20 min
  6. Python in depth

    Advanced11 lessons · 237 min

    Generators, decorators, typing, async code, testing and the secrets of professional Python.

    1. 17Iterators and generatorsHow a `for` loop really works: the iteration protocol, `__iter__`/`__next__`, generators with `yield`, lazy evaluation, `yield from` and memory-friendly pipelines.22 min
    2. 18Decorators and closuresFunctions as objects, the LEGB rule, closures and `nonlocal`, writing decorators, decorators with arguments, `functools.wraps` and caching with `lru_cache`.22 min
    3. 19Context managers and the with statementWhat `with` really does: `__enter__` and `__exit__`, handling exceptions in `__exit__`, writing managers with `contextlib.contextmanager`, and the ready-made tools `suppress`, `redirect_stdout` and `ExitStack`.18 min
    4. 20Type hints and dataclassesWriting types into your code: `list[int]`, `int | None`, `Callable`, `Literal`, generics and `Protocol`, checking with mypy, plus `@dataclass`, `field`, `frozen`, `order` and `slots`.22 min
    5. 21Advanced OOP: special methods, properties and the MROMake your classes behave like built-in types: `__repr__`/`__str__`, `__eq__`/`__lt__`/`__hash__`, operator overloading, the container protocol, `@property`, class and static methods, the MRO, `super()` and `abc.ABC`.25 min
    6. 22Structural pattern matching: match-case`match`/`case` from Python 3.10: literal, capture and wildcard patterns, sequence, mapping and class patterns, OR-patterns, `as` and guards, built into a text command parser and a JSON event dispatcher.22 min
    7. 23Regular expressions with reSearching text by pattern: `re.search`, `findall`, `finditer`, character classes and quantifiers, groups and named groups, greedy vs lazy matching, `sub`, `split`, flags and `compile`.22 min
    8. 24Asynchronous Python: async and awaitRun waiting-heavy work concurrently: coroutines, `await`, the event loop, `asyncio.run`, `gather`, `create_task`, `TaskGroup`, timeouts, `async for` and the dangers of blocking the loop.22 min
    9. 25Packages, modules and virtual environmentsStructure a project like a professional: modules vs packages, `__init__.py`, relative imports, `if __name__ == '__main__'`, `venv`, `pip`, `requirements.txt`, `pyproject.toml` and version specifiers.20 min
    10. 26Testing with pytestWrite automated tests: how pytest finds tests, assert rewriting, checking exceptions and floats, fixtures, `tmp_path` and `parametrize`.20 min
    11. 27Performance, Big-O and the collections moduleWrite fast code: Big-O notation, the cost of list, dict and set operations, measuring with `timeit` and `cProfile`, `Counter`, `defaultdict`, `deque`, `namedtuple` and `itertools`.22 min
  7. The standard library in depth

    Advanced4 lessons · 90 min

    The ready-made modules that ship with Python: dates and times, time zones and other everyday tools.

    1. 28Dates and times: datetime and time zonesCalculations with `date`, `time`, `datetime` and `timedelta`, `strftime`/`strptime` and ISO 8601, naive and aware times, storing in UTC, Asia/Baku and other zones with `zoneinfo`, daylight saving traps, adding months and counting working days.24 min
    2. 29Unicode, encodings and bytesCode points, `ord` and `chr`, `str` versus `bytes`, `encode`/`decode` with UTF-8, `errors=` strategies and garbled text (mojibake), NFC/NFD normalization, case pitfalls with `İ`/`ı` and `casefold`, `bytearray`, reading files in the right encoding and the BOM.23 min
    3. 30Sorting, bisect and heapq`sorted` and `list.sort`, key functions and `reverse`, stability and multi-key sorts, `itemgetter`/`attrgetter`, sorting by the Azerbaijani alphabet, `bisect` for sorted inserts and counting ranges, `heapq` for top-k, priority queues and merging, and a leaderboard project.22 min
    4. 31Configuration files and environment variablesEnvironment variables with `os.environ` and defaults, converting strings to types, `.env` files (our own parser and python-dotenv), INI with `configparser`, JSON and TOML with `tomllib`, the precedence defaults → file → environment → command line with `ChainMap`, and keeping secrets out of code and repositories.21 min
  8. Scripts and command-line tools

    Advanced3 lessons · 66 min

    Logging for long-running scripts, command-line interfaces and running other programs.

    1. 32The file system: pathlib and shutil`Path` objects and the `/` operator, the parts of a path, searching with `exists`, `iterdir`, `glob` and `rglob`, reading and writing text and bytes, `mkdir` and `stat`, copying, moving, archiving and safely deleting with `shutil`, temporary folders and a folder-report project.22 min
    2. 33Logging with the logging moduleWhy `print` is not enough: levels, `basicConfig` and formats, loggers, handlers and formatters, the logger hierarchy with `getLogger(__name__)`, logging to a file and `RotatingFileHandler`, `logger.exception`, configuration with `dictConfig`, and what must never be logged.22 min
    3. 34Command-line apps: argparse and click`sys.argv` and its limits; `argparse`: positional and optional arguments, types, `choices`, defaults, flags, `nargs`/`count`/`append`, help text and errors, subcommands, exit codes and `main(argv)`; `click` with decorators, groups and testing with `CliRunner`.22 min
  9. Code quality, testing and packaging

    Advanced1 lessons · 24 min

    Test doubles (mocks) and testing code reliably.

    1. 35Test doubles with unittest.mockWhy tests replace the network, the clock and randomness; passing dependencies in and fakes; `Mock` and `MagicMock`, `return_value` and `side_effect`, `autospec`; asserting calls; `patch` as a decorator and a context manager and where to patch; patching time and network calls; pytest’s `monkeypatch` and the danger of over-mocking.24 min
  10. Web and automation

    Advanced8 lessons · 164 min

    JSON and CSV files, APIs, a web service with FastAPI and scripts that automate everyday work.

    1. 36Working with JSON and CSVTurn data into text and back with the `json` module, keep Azerbaijani letters readable with `ensure_ascii=False`, read and write tables correctly with the `csv` module, and handle files with `pathlib`.20 min
    2. 37Databases in Python: sqlite3Working with the standard `sqlite3` module: connections and cursors, `CREATE`/`INSERT`/`SELECT`, parameters that prevent SQL injection, `executemany`, `row_factory`, transactions with `with`, a small library app and a first look at SQLAlchemy.22 min
    3. 38Web APIs and the requests libraryHow HTTP works: methods, status codes, headers and JSON. GET and POST requests with `requests`, `params`, `headers`, `timeout`, `raise_for_status`, error handling and keeping API keys safe.18 min
    4. 39Pydantic: data validationValidating outside data with Pydantic v2: models, lax and strict mode, `Field` constraints, `Annotated` and `Literal`, field and model validators, nested models and JSON, aliases, settings with `pydantic-settings` and use in FastAPI, with a project that checks applications.22 min
    5. 40Web services with FastAPIBuild a small REST API with FastAPI: path and query parameters, validation with Pydantic models, 201 and 404 responses, automatic docs (`/docs`), running the server on your computer and testing it with `TestClient`.20 min
    6. 41SQLAlchemy: databases with an ORMDatabases in the SQLAlchemy 2.0 style: the engine and transactions, Core and the ORM, declarative models, adding, changing and deleting with a Session, queries with `select()`, relationships and the N+1 problem, migrations with Alembic, with SQLite examples.22 min
    7. 42Automation scriptsHand routine work over to Python: sort files with `pathlib` and `shutil`, find old files with `datetime`, build a command-line interface with `argparse`, keep a log with `logging`, and run the script on schedule with cron or Task Scheduler.20 min
    8. 43Excel automation with openpyxlReading and writing Excel files with Python: workbooks, sheets and cells, formulas and the `data_only` trap, styles and number formats, charts, `read_excel` and `ExcelWriter` with pandas, with a project that automates a weekly sales report.20 min
  11. Web apps with Flask and FastAPI

    Advanced3 lessons · 75 min

    Server-rendered apps with Flask and production-style APIs with FastAPI.

    1. 44Flask: your first web appBuild a small multi-page site with Flask: routes and URL variables, query parameters, Jinja2 templates and inheritance, static files, JSON responses, the development server with debug mode, and testing pages with the test client.25 min
    2. 45Flask: forms, sessions and a databaseA to-do app in Flask: POST forms and validating input, Post/Redirect/Get and flash messages, signed sessions and the secret key, one SQLite connection per request, protection against SQL injection and CSRF, and blueprints.25 min
    3. 46FastAPI: dependencies and databases`Depends` and dependency trees, one SQLAlchemy session per request with a `yield` dependency, CRUD with Pydantic schemas, status codes and `HTTPException`, routers, async and background tasks, and tests with `TestClient` and a temporary database.25 min
  12. Django

    Advanced2 lessons · 50 min

    The batteries-included framework: projects, models, the admin and templates.

    1. 47Django: projects, apps and the first pageDjango, the “batteries included” framework: `startproject` and `startapp`, `settings.py`, the MVT structure and the path of a request, URLconf and path converters, view functions, template inheritance, `runserver`, the test `Client` and the security settings for production.25 min
    2. 48Django: models, migrations and the adminA blog with posts, comments and tags: model fields and options, `makemigrations`/`migrate`, the QuerySet API (filter, exclude, get, lookups, F and Q), ForeignKey and ManyToMany relationships, N+1 and `select_related`, the admin site and the Django shell.25 min
  13. Web scraping and browser automation

    Advanced1 lessons · 22 min

    Parsing HTML and collecting data from websites politely and within the rules.

    1. 49Parsing HTML with BeautifulSoupThe HTML tree, `BeautifulSoup(html, 'html.parser')`, `find`/`find_all` and `select` with CSS selectors, attributes and relative links, turning tables into lists and pandas DataFrames, robots.txt and polite, legal scraping, the examples run in the browser.22 min
  14. Data science: NumPy, pandas, matplotlib

    University7 lessons · 175 min

    Array computing, tabular data analysis, charts, statistics and machine learning with scikit-learn.

    1. 50NumPy basics: arraysMeet the NumPy array (ndarray): type and shape, creating arrays, reproducible random numbers, indexing, slicing, boolean masks and aggregation along axes.25 min
    2. 51NumPy: vectorization and linear algebraReplace loops with array expressions, master the broadcasting rules, reshape arrays, and use `np.linalg` to solve linear systems and find determinants and eigenvalues.25 min
    3. 52pandas basics: Series and DataFrameWork with tabular data in pandas: Series and DataFrame, reading CSV, `head`, `info`, `describe`, selecting with `loc` and `iloc`, filtering, sorting and new columns.25 min
    4. 53Data analysis with pandasThe core tools for real data: missing values, `groupby` and `agg`, joining tables with `merge`, `pivot_table`, `map` and `apply`, dates, and a mini analysis of a café chain's sales.25 min
    5. 54Visualization with matplotlibBuild line, bar and scatter charts, histograms and subplots, label axes, titles and legends properly, choose the number of bins and learn the rules of honest, readable charts.25 min
    6. 55Statistics with PythonDescriptive statistics, outliers, the normal distribution and `scipy.stats`, the central limit theorem, confidence intervals, the t-test and correlation, with formulas, worked examples and runnable code.25 min
    7. 56Machine learning with scikit-learnscikit-learn's unified interface: splitting data, linear and logistic regression, decision trees, MSE, R², accuracy, the confusion matrix, precision and recall, cross-validation and pipelines that protect against data leakage.25 min
  15. Scientific computing and image processing

    University3 lessons · 69 min

    Numerical methods with SciPy, exact mathematics with SymPy and image processing with Pillow and OpenCV.

    1. 57Scientific computing with SciPySciPy’s main toolboxes in practice: finding minima and roots (`optimize`), fitting a model to data (`curve_fit`), definite integrals and differential equations (`integrate`), interpolation, linear systems and probability distributions, with checks by hand and a mini project on a cooling cup of tea.25 min
    2. 58SymPy: symbolic mathematicsExact mathematics with SymPy: symbols and fractions, expanding and factorising, equations and inequalities with `solve` and `solveset`, derivatives, integrals, limits and Taylor series, matrices, graphs and `lambdify`, with a project that investigates a function completely.22 min
    3. 59Image processing with Pillow and OpenCVAn image is a NumPy array of pixels: coordinates, channels and the grayscale formula; opening, resizing, cropping, drawing and saving with Pillow; BGR, colour spaces, blur, thresholds, edges and contours with OpenCV, with a coin-counting project.22 min
  16. AI and deep learning with PyTorch

    University7 lessons · 166 min

    From gradient descent to neural networks: tensors, autograd, training loops, CNNs and transformers.

    1. 60Machine learning conceptsTypes of machine learning, features and labels, data splits, loss functions, gradient descent, overfitting and the bias-variance trade-off, with runnable NumPy examples.25 min
    2. 61PyTorch: tensorsInstall PyTorch and learn its core data type: creating tensors, dtype and shape, reshape/view, indexing, broadcasting, matrix multiplication with @, GPUs and NumPy interop.22 min
    3. 62PyTorch: autograd and automatic differentiationHow PyTorch computes derivatives for you: the computational graph, requires_grad, backward() and .grad, the chain rule, gradient accumulation, torch.no_grad() and gradient descent with autograd.22 min
    4. 63PyTorch: building neural networksFrom an artificial neuron to a multilayer network: z = w·x + b, activation functions (ReLU, sigmoid, tanh, softmax), nn.Linear layers, nn.Module and nn.Sequential, the forward pass and parameter counts.22 min
    5. 64PyTorch: the training loopDataset and DataLoader, loss functions, the SGD and Adam optimizers, the full training loop, eval mode and accuracy, saving a model with state_dict, by training a small classifier on synthetic data.25 min
    6. 65Convolutional neural networks (CNNs)Images as tensors (C × H × W), convolution and the output-size formula, filters, pooling, a small CNN for 28 × 28 images with a shape walk-through, MNIST with torchvision and transfer learning.25 min
    7. 66Transformers and large language modelsTokens and embeddings, self-attention Attention(Q, K, V) = softmax(QKᵀ/√dₖ)·V, multi-head attention, positional encoding, encoders and decoders, how LLMs learn by next-token prediction, fine-tuning, Hugging Face and responsible AI.25 min