Перейти к содержимому

Основной текст этой страницы на английском языке.Перевести страницу

Навыки и технологии

Python roadmap

Learn Python from zero to writing clean, tested, professional code. Python is the main language for AI, data science, automation and many backends.

Время
⏱ 6–8 weeks
Level
Beginner
Steps
6 steps
Cheat sheet ↓6 interview Q&As ↓
Поделиться

The roadmap

Click a step to open the full guide.

Python cheat sheet

The essentials on one screen. Bookmark it for revision.

Syntax

f-stringf"Total: {total:.2f}"
List comprehension[x for x in xs if x]
Dict comprehension{k: v for k, v in pairs}
Unpackinga, b = b, a
Safe dict getd.get("key", default)
Enumerateна i, x in enumerate(xs): год
Zipна a, b in zip(xs, ys): год
Lambda sortsorted(xs, key=lambda x: x["price"])

Commands

New venvpython -m venv .venv
Activate (Windows).venv\Scripts\activate
Activate (Mac/Linux)source .venv/bin/activate
Installpip install httpx
Run testspytest -q
Lint + formatruff check . && ruff format .

Improve performance

  • Use the right data structure: dicts/sets for lookups instead of searching lists.
  • Use built-ins (sum, sorted, max) and comprehensions; they run in fast C code.
  • Use async or threads for many network calls; multiprocessing for CPU-heavy work.
  • Profile before optimising: python -m cProfile script.py shows where time goes.
  • Use generators for large data so you don't load everything into memory.
  • Cache repeated expensive calls with functools.lru_cache.

Security checklist

  • Never hard-code secrets; use environment variables.
  • Never use eval()/exec() on user input.
  • Use parameterised SQL queries, never string formatting.
  • Pin and audit dependencies (pip-audit); install only trusted packages.
  • Validate all external input (Pydantic) and set timeouts on network calls.

Most important interview questions

Click a question to see a strong answer. Each step also has its own questions.

1What are Python's main data types?

int, float, bool, str, list, tuple, dict, set and None; plus bytes for binary data.

2Что такое a generator?

A function that uses yield to produce values one at a time, saving memory for large or infinite sequences.

3Explain list vs dict lookup performance.

Checking x in list scans every item (O(n)); x in dict/set uses hashing (O(1) on average).

4Что такое the difference between deep and shallow copy?

A shallow copy copies the outer container but shares nested objects; a deep copy (copy.deepcopy) copies everything recursively.

5How does Python manage memory?

Reference counting plus a cyclic garbage collector; objects are freed when no references remain.

6What are decorators used for in real projects?

Adding cross-cutting behaviour such as routes in web frameworks, caching, retries, logging, timing and access checks.

Дорожных карт: Related

1

Python · Step 1 of 6 · 1 week

Basics: values, control flow, functions

Write your first real programs.

Start by writing small programs that do something useful: a tip calculator, a password checker, a unit converter. Functions are the most important idea: name a piece of logic and reuse it.

What you'll learn

  • Numbers, strings and booleans
  • if / elif / else
  • на and while loops год
  • Functions and return values
  • f-strings
  • Reading errors

How a Python program runs

  1. Your .py file
  2. Python interpreter
  3. Bytecode
  4. Runs line by line
  5. Output / errors

Key concepts

Variable
A name that points to a value. Python figures out the type for you.
Indentation
Spaces that define blocks in Python (use 4 spaces).
Function
Reusable, named logic with inputs (parameters) and an output (return).

Step by step

  1. 1.1

    Install and run

    Install Python 3.12+, open a terminal, run python --version, then write hello.py.

  2. 1.2

    Values and variables

    Numbers, strings, booleans; name = "Asha"; print with f-strings.

  3. 1.3

    Decisions and loops

    if/elif/else, for over lists and range(), while with a stop condition.

  4. 1.4

    Functions

    Wrap logic in def, take parameters, return results; add type hints.

def grade(score: int) -> str:
    if score >= 90:
        return "A"
    elif score >= 75:
        return "B"
    return "C"

for s in [95, 80, 60]:
    print(f"{s} -> {grade(s)}")

Notes

  • Indentation is part of Python's syntax.
  • Use f-strings for formatting: f"Hi {name}".

Tips & tricks

  • Type every example yourself instead of copying.
  • Read the last line of an error first.

Interview questions

Что такое the difference between `==` and `is`?

== compares values (are they equal?). is compares identity (are they the same object?). Use is only for None, True, False.

Is Python compiled or interpreted?

Both: source is compiled to bytecode, which the Python virtual machine interprets. In practice it behaves like an interpreted language.

The quick way to study this

Do one interactive beginner course in a week, then build three tiny programs.

2

Python · Step 2 of 6 · 1 week

Data structures

Lists, dictionaries, sets and tuples.

Most real programs are about organising data. Dictionaries map keys to values and are used everywhere, including JSON from APIs. Comprehensions build lists and dicts in one readable line.

What you'll learn

  • Lists and slicing
  • Dictionaries
  • Sets
  • Tuples and unpacking
  • Comprehensions
  • Sorting with keys

Which data structure?

list

  • Ordered
  • Duplicates OK
  • Find by position

dict

  • Key → value
  • Fast lookup by key
  • JSON-like data

set

  • Unique items
  • Fast 'is it in?'
  • Remove duplicates

Key concepts

Mutable vs immutable
Lists/dicts/sets can change; strings/tuples/numbers can't.
Big-O of lookups
Dict and set lookups are O(1) on average; searching a list is O(n).
Comprehension
A compact way to build a list, dict or set from another iterable.

Step by step

  1. 2.1

    Lists

    Ordered and changeable: append, slicing a[1:3], sorted().

  2. 2.2

    Dictionaries

    Key → value lookups: d.get(key, default), .items() in loops.

  3. 2.3

    Sets and tuples

    Sets for unique items and fast membership; tuples for fixed records.

  4. 2.4

    Comprehensions

    [x*2 for x in nums if x > 0] builds lists in one readable line.

orders = [{"item": "tea", "qty": 2}, {"item": "coffee", "qty": 1}, {"item": "tea", "qty": 3}]

totals: dict[str, int] = {}
for o in orders:
    totals[o["item"]] = totals.get(o["item"], 0) + o["qty"]

print(totals)  # {'tea': 5, 'coffee': 1}
print(sorted(totals, key=totals.get, reverse=True))

Notes

  • Dictionary lookups are fast; use them instead of searching lists.
  • Sets remove duplicates instantly.

Tips & tricks

  • Practise turning loops into comprehensions, but keep them readable.

Interview questions

List vs tuple?

Lists are mutable and used for collections that change. Tuples are immutable, slightly faster, hashable (can be dict keys) and used for fixed records.

How do you remove duplicates from a list while keeping order?

list(dict.fromkeys(items)): dict keys are unique and keep insertion order.

The quick way to study this

Solve 20 small problems that use each structure.

3

Python · Step 3 of 6 · 1 week

Files, modules and packages

Organise code and use libraries.

Split code into modules and use virtual environments so each project has its own packages. pathlib makes file paths clean and cross-platform.

What you'll learn

  • Reading and writing files
  • JSON and CSV
  • Modules and imports
  • Virtual environments
  • Installing packages
  • pathlib

A tidy Python project

  • my_project/
  • .venv/ (not committed)
  • pyproject.toml
  • src/my_project/
  • __init__.py
  • main.py
  • utils.py
  • tests/
  • test_utils.py

Key concepts

Context manager
with blocks that clean up automatically (close files, release locks).
Module
A .py file you can import.
Virtual environment
An isolated set of packages for one project.

Step by step

  1. 3.1

    Read and write files

    with open(path) as f: closes files automatically.

  2. 3.2

    JSON and CSV

    Use the json and csv modules; pathlib.Path на paths. год

  3. 3.3

    Modules and packages

    Split code into files; import what you need; add __init__.py на packages. год

  4. 3.4

    Virtual environments

    python -m venv .venv (or uv), then install packages per project.

Notes

  • Use with open(...) so files always close.
  • One virtual environment per project.

Tips & tricks

  • Learn a modern package manager such as uv; it is very fast.

Interview questions

Why use virtual environments?

So each project has its own package versions and doesn't break others; it also makes installs reproducible.

The quick way to study this

Build a script that reads a CSV, summarises it and writes JSON.

4

Python · Step 4 of 6 · 1 week

Classes, errors and type hints

Write structured, safer code.

Classes group data with behaviour. Dataclasses remove boilerplate for simple data holders. Type hints document your code and let tools catch mistakes.

What you'll learn

  • Classes and methods
  • Dataclasses
  • Exceptions and try/except
  • Custom exceptions
  • Type hints
  • Pydantic models

Error handling flow

  1. try: risky code
  2. Error raised?
  3. except: handle it
  4. else: success path
  5. finally: clean up

Key concepts

Class vs object
A class is the blueprint; an object is one built from it.
Inheritance
A class reusing and extending another class.
Exception
An error signal you can catch and handle.

Step by step

  1. 4.1

    Classes

    Bundle data and behaviour; __init__ sets attributes; methods take self.

  2. 4.2

    Dataclasses

    @dataclass writes __init__, __repr__ and comparisons for you.

  3. 4.3

    Exceptions

    try/except specific errors; raise your own; finally на clean-up. год

  4. 4.4

    Type hints and Pydantic

    Hints document intent; Pydantic validates data from outside.

from dataclasses import dataclass

@dataclass
class Product:
    name: str
    price: float

    def with_gst(self, rate: float = 0.18) -> float:
        return round(self.price * (1 + rate), 2)

print(Product("Fan", 2499).with_gst())

Notes

  • Catch specific exceptions, not bare except:.

Tips & tricks

  • Use Pydantic when data comes from outside (APIs, users, AI models).

Interview questions

What are `*args` and `**kwargs`?

*args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict.

Что такое a decorator?

A function that takes a function and returns a new one, adding behaviour (logging, caching, routes) without changing the original code. Used with @name.

The quick way to study this

Refactor one script into a small class with type hints.

5

Python · Step 5 of 6 · 1 week

APIs, async and automation

Talk to the internet and automate tasks.

Calling APIs is the core of modern Python work, including AI. Async lets one program wait on many network calls at once.

What you'll learn

  • HTTP requests with httpx or requests
  • Working with JSON APIs
  • async/await basics
  • Environment variables
  • Scheduling scripts

Sync vs async API calls

Sync (one by one)

  • Call A, wait
  • Call B, wait
  • Call C, wait
  • Total ≈ A + B + C

Async (together)

  • Start A, B, C
  • Wait for all
  • Total ≈ slowest one

Key concepts

Async I/O
Doing other work while waiting на network or disk. год
Timeout
A maximum wait time so your program never hangs forever.
Retry with backoff
Try again after increasing delays when a request fails temporarily.

Step by step

  1. 5.1

    HTTP requests

    httpx.get(url, timeout=10), check status, read .json().

  2. 5.2

    Async

    async def, await, and asyncio.gather() to run calls together.

  3. 5.3

    Secrets

    Read keys from environment variables or a .env file (not committed).

  4. 5.4

    Automate

    Schedule scripts with cron / Task Scheduler or a job runner.

import httpx

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

Notes

  • Keep API keys in environment variables, never in code.

Tips & tricks

  • Add timeouts and retries to every network call.

Interview questions

Что такое the GIL and does it matter?

The Global Interpreter Lock lets only one thread run Python bytecode at a time. It limits CPU-bound threading (use multiprocessing), but not I/O-bound work, where threads or async work well.

The quick way to study this

Write a script that calls two APIs and combines the results.

6

Python · Step 6 of 6 · 1 week

Testing and clean code

Professional habits.

Tests let you change code with confidence. Linters and formatters keep code consistent so reviews focus on logic.

What you'll learn

  • pytest
  • Fixtures
  • Linting and formatting (Ruff)
  • Debugging
  • Logging
  • Project structure

Test-driven loop

  1. Write a failing test
  2. Write code to pass it
  3. Refactor
  4. Run all tests

Repeats as a loop

Key concepts

Unit test
A small test of one function's behaviour.
Fixture
Reusable setup for tests.
CI
Automatically running tests on every push.

Step by step

  1. 6.1

    Write tests

    pytest functions named test_*; use assert.

  2. 6.2

    Fixtures

    Reusable setup (temp files, test data) with @pytest.fixture.

  3. 6.3

    Lint and format

    Ruff for linting and formatting; run on save and in CI.

  4. 6.4

    Log, don't print

    Use the logging module with levels (INFO, WARNING, ERROR).

Notes

  • Test behaviour, not implementation details.

Tips & tricks

  • Run tests automatically on every push with GitHub Actions.

Interview questions

How do you test code that calls an external API?

Mock or fake the HTTP layer (e.g. with a test client or respx/responses), test success and error cases, and keep a few slower integration tests separately.

The quick way to study this

Add pytest and Ruff to one project and reach a passing test suite.

Поделиться этой страницей