Python с нуля: основы программирования и практика

Курс для начинающих, который шаг за шагом познакомит с Python и базовыми принципами программирования. Вы научитесь писать простые программы, работать с данными, файлами и модулями, а также применять ключевые инструменты языка на практике.

1. Введение в Python и настройка среды

Введение в Python и настройка среды

Python — популярный язык программирования, который подходит для первых шагов в коде и при этом используется в реальных проектах: веб-разработка, анализ данных, автоматизация, тестирование, боты и многое другое.

В этой статье вы:

  • Поймёте, что такое Python и как он запускается
  • Установите Python и проверите, что всё работает
  • Выберете редактор кода
  • Научитесь запускать программы из файла и из интерактивного режима
  • Настроите изоляцию проектов через виртуальные окружения
  • Что такое Python

    Python — это язык программирования и одновременно набор инструментов.

    Когда вы “пишете на Python”, обычно участвуют три части:

  • Исходный код: текстовый файл с расширением .py
  • Интерпретатор Python: программа, которая читает ваш код и выполняет его
  • Библиотеки: готовые модули (как встроенные, так и устанавливаемые отдельно)
  • !Схема показывает, как код попадает в интерпретатор и превращается в результат, а библиотеки подключаются по мере надобности

    Где писать и запускать Python

    Есть два основных способа запускать код:

  • Интерактивный режим (REPL): вы вводите команды по одной и сразу видите результат
  • Запуск файла: вы пишете программу в .py-файле и запускаете её целиком
  • Для обучения удобно сочетать оба подхода: в REPL пробовать маленькие кусочки кода, а в файлах собирать полноценные программы.

    Установка Python

    Официальный сайт Python: Python.org

    Важно:

  • Скачивайте Python только из доверенных источников (в идеале — с Python.org)
  • Для курса выбирайте актуальную стабильную версию Python 3
  • Windows

  • Откройте страницу загрузки: Python для Windows
  • Скачайте установщик (обычно “Windows installer (64-bit)”)
  • Запустите установщик
  • Обязательно отметьте галочку Add python.exe to PATH
  • Завершите установку
  • macOS

  • Откройте страницу загрузки: Python для macOS
  • Скачайте установщик macOS 64-bit universal2 installer
  • Установите Python как обычное приложение
  • Linux

    Во многих дистрибутивах Python уже установлен. Проверьте в терминале:

    Если команды нет, установите Python через менеджер пакетов вашей системы (названия пакетов и команды зависят от дистрибутива).

    Проверка установки

    Откройте терминал (или PowerShell на Windows) и выполните:

    Если команда не найдена, попробуйте:

    Ожидаемое поведение: вы увидите версию Python (например, Python 3.x.y).

    Первый запуск Python

    Интерактивный режим

    Запустите в терминале:

    Вы попадёте в интерактивную среду. Попробуйте:

    Чтобы выйти:

  • Windows: нажмите Ctrl+Z, затем Enter
  • macOS/Linux: нажмите Ctrl+D
  • Запуск программы из файла

  • Создайте папку проекта (например, python-course)
  • Внутри создайте файл hello.py
  • Добавьте в файл:
  • Запустите из терминала, находясь в папке с файлом:
  • Выбор редактора кода

    Вам нужен редактор, который умеет работать с Python и помогает находить ошибки.

    Популярные варианты:

    | Инструмент | Для кого подходит | Плюсы | Минусы | |---|---|---|---| | Visual Studio Code | Большинству новичков и практиков | Бесплатный, лёгкий, много расширений | Нужно поставить расширение Python | | PyCharm Community | Тем, кто хочет “всё из коробки” | Мощные подсказки, удобные проекты | Может казаться тяжеловатым |

    Если выбираете VS Code, установите расширение Python от Microsoft из встроенного магазина расширений.

    Терминал, рабочая папка и пути

    В программировании важно понимать простую идею: команда запускается в некоторой папке.

    Практика, которая поможет избежать ошибок:

  • Делайте отдельную папку под каждый проект
  • Запускайте команды из терминала, открытого именно в папке проекта
  • Следите, какой файл вы запускаете: python имя_файла.py
  • Установка пакетов и менеджер pip

    Python умеет подключать сторонние библиотеки. Обычно они ставятся командой pip.

    Проверка pip:

    Установка пакета (пример):

    Полезные справочные страницы:

  • Документация pip
  • Виртуальные окружения (venv)

    Одна из главных привычек в Python — изолировать зависимости проектов.

    Зачем это нужно: разные проекты могут требовать разные версии библиотек. Если ставить всё “в систему”, легко получить конфликт зависимостей.

    Виртуальное окружение — это папка внутри проекта (или рядом), где хранится отдельный Python и отдельные установленные пакеты для этого проекта.

    Официальная документация: venv — создание виртуальных окружений

    Создание и активация venv

  • Перейдите в папку проекта:
  • Создайте окружение (назовём его .venv):
  • Активируйте:
  • Windows (PowerShell):

    Windows (cmd):

    macOS/Linux:

  • Убедитесь, что ставите пакеты именно в окружение:
  • Деактивация окружения:
  • Частые проблемы и как их решить

  • Команда python не найдена
  • - Windows: переустановите Python и убедитесь, что включили Add python.exe to PATH - macOS/Linux: попробуйте python3 вместо python

  • Открывается Microsoft Store вместо Python (Windows)
  • - Установите Python с Python.org и проверьте настройки “App execution aliases” в Windows

  • pip ставит пакеты “не туда”
  • - Используйте python -m pip ... вместо просто pip ... - Проверьте, активировано ли виртуальное окружение

    Итоги

    Теперь у вас есть базовая рабочая среда:

  • Python установлен и запускается
  • Вы умеете запускать код в REPL и из .py-файла
  • Вы выбрали редактор кода
  • Вы знаете, что такое pip и виртуальные окружения venv
  • В следующей статье мы начнём писать код системно: переменные, типы данных и простые операции — так, чтобы вы уверенно читали и создавали небольшие программы.

    2. Типы данных, переменные и ввод-вывод

    Типы данных, переменные и ввод-вывод

    В прошлой статье вы установили Python, выбрали редактор и научились запускать код из файла и в интерактивном режиме. Теперь начнём писать программы системно: разберём, как хранить данные, как их называть и как общаться с пользователем через ввод-вывод.

    В этой статье вы:

  • Поймёте, что такое значение, тип данных и переменная
  • Научитесь использовать основные типы данных Python
  • Разберётесь с print() и input()
  • Узнаете про преобразование типов и частые ошибки
  • Значения, типы данных и переменные

    Значение

    Значение — это конкретные данные: число 10, строка "привет", логическое True.

    Тип данных

    Тип данных описывает, что это за значение и какие операции с ним возможны.

    Например:

  • у числа можно складывать и умножать
  • у строки можно склеивать (конкатенировать)
  • Проверить тип можно функцией type().

    Переменная

    Переменная — это имя, которое ссылается на значение. Вы “кладёте” значение в переменную с помощью оператора присваивания =.

    !Схема показывает, что переменная — это имя, которое указывает на значение определённого типа

    Основные типы данных в Python

    Ниже — базовые типы, которых достаточно для первых программ.

    | Тип | Как выглядит | Для чего | Пример | |---|---|---|---| | int | целое число | счётчики, количество, индексы | items = 3 | | float | число с точкой | измерения, проценты, расчёты | pi = 3.14 | | str | строка в кавычках | текст, имена, сообщения | city = "Москва" | | bool | True или False | условия, проверки | is_admin = False | | NoneType | None | “значения нет” или “ещё не задано” | result = None |

    Строки str

    Строка — это текст. В Python строку обычно записывают в двойных или одинарных кавычках.

    Частые операции:

  • Склеивание строк: "Привет, " + name
  • Длина строки: len(message)
  • Числа int и float

    int — целые числа, float — числа с дробной частью.

    Важно: при смешивании int и float результат обычно становится float.

    Логический тип bool

    bool используется там, где ответ “да/нет”.

    Этот тип пригодится, когда вы начнёте писать условия if.

    Имена переменных

    Хорошие имена переменных делают код понятным.

    Правила:

  • Можно использовать буквы, цифры и _
  • Имя не может начинаться с цифры
  • Python различает регистр: age и Age — разные имена
  • Нельзя использовать ключевые слова Python (например, if, for, class)
  • Примеры хороших имён:

  • user_name
  • total_price
  • is_ready
  • Примеры плохих имён:

  • a (слишком непонятно, кроме совсем маленьких примеров)
  • 1name (нельзя начинать с цифры)
  • sum (так называется встроенная функция, лучше не “перетирать”)
  • Вывод на экран: print()

    Функция print() выводит текст и значения в консоль.

    Несколько значений в print()

    print() умеет выводить несколько аргументов через запятую. По умолчанию между ними ставится пробел.

    Полезные параметры:

  • sep задаёт разделитель между аргументами
  • end задаёт, чем заканчивается строка (по умолчанию это перевод строки)
  • Форматирование строк через f-строки

    Самый удобный способ подставлять значения в текст — f-строки.

    Внутри {...} можно писать выражения.

    Ввод от пользователя: input()

    Функция input():

  • показывает подсказку (если вы её передали)
  • ждёт, пока пользователь введёт строку и нажмёт Enter
  • возвращает введённый текст как строку (str)
  • Ключевой момент:

  • input() всегда возвращает str, даже если пользователь ввёл 123
  • Преобразование типов

    Чтобы из строки сделать число, используют функции int() и float().

    Если ожидается дробное число:

    Частая ошибка новичков

    Если не преобразовать тип, получится ошибка при попытке сложить строку и число.

    Что будет, если пользователь ввёл не число

    int("abc") вызовет ошибку ValueError. Пока что достаточно знать: программа “упадёт”, если ввод некорректный. Позже вы научитесь обрабатывать такие ситуации аккуратно.

    Небольшая программа: диалог с пользователем

    Соберём всё вместе в один файл, например profile.py.

    Запустите в терминале из папки проекта:

    Итоги

    Теперь вы умеете писать простые программы, которые:

  • хранят данные в переменных
  • используют базовые типы: int, float, str, bool, None
  • выводят результат через print()
  • получают ввод пользователя через input()
  • преобразуют строки во входе в числа через int() и float()
  • В следующей теме обычно идут условия и ветвления: вы научитесь принимать решения в коде на основе True и False.

    3. Условия, циклы и логика программ

    Conditions, loops, and program logic

    In the previous articles you installed Python, learned how to run scripts, and practiced variables, basic data types, and input/output with print() and input(). Now you will learn how to control the flow of a program: how to make decisions, repeat actions, and combine checks into clear logic.

    In this article you will:

  • Use comparisons and boolean logic (True / False)
  • Write branching code with if, elif, else
  • Repeat actions with while and for
  • Control loops with break and continue
  • Avoid common mistakes like infinite loops and off-by-one errors
  • Boolean values and comparisons

    A lot of programming is answering questions like:

  • “Is the user old enough?”
  • “Is the input empty?”
  • “Did we reach the last element?”
  • In Python, the type for yes/no is bool with values True and False.

    Comparison operators

    Comparisons produce a boolean result.

    | Operator | Meaning | Example | Result | |---|---|---|---| | == | equal | 5 == 5 | True | | != | not equal | 5 != 7 | True | | < | less than | 3 < 10 | True | | <= | less or equal | 10 <= 10 | True | | > | greater than | 7 > 9 | False | | >= | greater or equal | 9 >= 1 | True |

    Example:

    Official reference: Python operators

    Boolean operators: and, or, not

    You can combine checks:

  • and is True only if both sides are True
  • or is True if at least one side is True
  • not flips the boolean value
  • Truth table summary:

    | A | B | A and B | A or B | |---|---|---|---| | False | False | False | False | | False | True | False | True | | True | False | False | True | | True | True | True | True |

    Reference: Boolean operations

    Branching with if, elif, else

    The if statement lets your program choose different paths.

    Basic if

    Key rules:

  • The condition must evaluate to True or False
  • The indented block runs only when the condition is True
  • Indentation is mandatory in Python (usually 4 spaces)
  • else

    elif for multiple cases

    The checks are evaluated top to bottom, and only the first matching branch runs.

    Reference: The if statement

    !Flowchart showing how Python chooses a branch in if/elif/else

    Truthiness: conditions without == True

    In Python, many values can be used directly in conditions. Some values are treated as “falsey”, meaning they behave like False in an if condition:

  • 0, 0.0
  • "" (empty string)
  • [], {}, set() (empty collections)
  • None
  • Example:

    This is usually clearer than comparing to an empty string.

    Loops: repeating actions

    A loop runs code multiple times. Python has two main loop types:

  • while for repeating “while a condition is true”
  • for for iterating over a sequence of values
  • Reference: More control flow tools

    while loop

    Basic pattern

    Important idea: a while loop must change something so the condition eventually becomes False. Otherwise you create an infinite loop.

    Input validation example

    Because input() returns a string, you often need to keep asking until the user enters valid data.

    Notes:

  • text.isdigit() checks if all characters are digits
  • This example rejects negatives and decimals on purpose to keep it simple
  • for loop

    A for loop iterates over items in a sequence.

    Iterating over a string

    Iterating over a list

    range() for counting

    range() produces a sequence of integers.

    This prints 0, 1, 2, 3, 4. That “stop value is not included” behavior is a common source of off-by-one mistakes.

    Typical patterns:

    Reference: The range() function

    Controlling a loop: break and continue

    break

    break exits the loop immediately.

    continue

    continue skips the rest of the current iteration and goes to the next one.

    Reference: The break and continue statements

    Common mistakes and how to avoid them

  • Indentation errors
  • Forgetting to update a while loop variable
  • Comparing numbers as strings
  • Off-by-one errors with range()
  • Comparing numbers as strings

    This compares strings, not numbers. Convert first:

    Infinite loop example

    Fix:

    Mini-program: simple command menu

    This combines input, conditions, and a loop.

    Summary

    You can now write programs that react and repeat:

  • Use comparisons and boolean operators to build conditions
  • Branch with if, elif, else
  • Repeat actions with while and iterate with for
  • Control loops with break and continue
  • Next, you typically go deeper into data structures (lists, dictionaries) and use loops with them to solve more practical problems.

    4. Функции, области видимости и ошибки

    Functions, scope, and errors

    Up to this point, you can write programs with variables, input/output, conditions, and loops. The next step is learning how to organize code so it stays readable as programs grow, and how to handle situations when something goes wrong.

    In this article you will learn:

  • How to create and use functions
  • How return works and why it matters
  • What scope means (where variables “live”)
  • How to understand and handle common errors with exceptions
  • Why functions matter

    A function is a named block of code that you can run (call) whenever you need it.

    Functions help you:

  • Avoid repeating the same code in multiple places
  • Make code easier to read by giving parts of logic clear names
  • Break a problem into smaller steps (which are easier to test and debug)
  • In practice, a typical beginner program evolves like this:

  • First: one file with top-to-bottom code
  • Then: add if and loops
  • Next: extract repeated or complex parts into functions
  • Defining and calling a function

    You define a function with def, a name, parentheses, and an indented block.

    Key ideas:

  • A function definition creates the function, but does not run it
  • Calling a function (writing greet()) runs its body
  • Parameters and arguments

    A function can accept inputs called parameters. When you call it, the values you pass are arguments.

    Here:

  • name is a parameter
  • "Alice" is an argument
  • Returning a value with return

    return sends a result back to the caller.

    Important behavior:

  • When Python hits return, it immediately exits the function
  • If a function finishes without return, it returns None
  • Common parameter patterns

    Official reference: Defining Functions

    Positional and keyword arguments

    Default values

    You can give a parameter a default value.

    A classic pitfall: mutable default values

    A frequent beginner mistake is using a list (or dictionary) as a default value.

    This happens because the default list is created once and reused across calls.

    A safe pattern is using None and creating a new list inside the function:

    Scope: where variables are visible

    Scope means the part of the code where a variable name is accessible.

    Two scopes matter most at the beginning:

  • Global scope: names defined at the top level of a file
  • Local scope: names defined inside a function
  • Local variables

    Variables created inside a function exist only inside that function.

    Reading a global variable

    A function can read a global variable.

    Assigning to a global variable

    If you assign to a name inside a function, Python treats it as local by default.

    To assign to a global variable, you must declare it with global.

    Use global rarely. Most of the time, prefer returning values from functions.

    Nested functions and nonlocal

    If you define a function inside another function, you may want to modify a variable from the outer function. For that, Python uses nonlocal.

    More details: The global statement and The nonlocal statement

    !A diagram of global vs local scope and how names are looked up during a function call

    Organizing a small program with functions

    A practical way to structure code is:

  • Input and validation in one function
  • Computation in another function
  • A main() function that coordinates everything
  • Example:

    This style keeps each function focused on one job, which makes debugging easier.

    Errors and exceptions

    When something goes wrong, Python usually raises an exception. If you do not handle it, the program stops and prints an error message with a traceback.

    Official reference: Errors and Exceptions

    Common exceptions you will see

    | Exception | Typical cause | Example | |---|---|---| | SyntaxError | invalid Python code | missing : after if | | NameError | using a name that does not exist | print(x) when x was never defined | | TypeError | operation on incompatible types | "2" + 2 | | ValueError | correct type, invalid value | int("abc") | | IndexError | invalid list index | numbers[10] for a short list | | ZeroDivisionError | division by zero | 10 / 0 |

    How to read a traceback

    A traceback shows:

  • The most recent line where the error happened
  • The chain of function calls that led there
  • Your usual workflow:

  • Read the last line (exception type and message)
  • Look at the file name and line number
  • Open that line and inspect variables and types
  • Handling errors with try / except

    You can prevent the program from crashing by catching exceptions.

    Good practices:

  • Catch specific exceptions, not a generic “everything”
  • Keep the try block small (only the lines that may fail)
  • else and finally

  • else runs if no exception happened
  • finally runs no matter what (useful for cleanup)
  • Raising your own errors with raise

    Sometimes you want to stop the program with a clear message when input is invalid.

    Summary

    You can now write cleaner and more reliable programs:

  • Define functions with def, pass data through parameters, and return results with return
  • Understand local vs global scope and why variables inside functions are isolated
  • Recognize common exceptions and read tracebacks to find the real problem
  • Handle errors using try / except and write safer input-processing code
  • 5. Коллекции: списки, кортежи, множества, словари

    Collections: lists, tuples, sets, dictionaries

    In the previous lessons you learned variables and types, then controlled program flow with if and loops, and finally organized code with functions and handled errors. Now you’ll learn collections—data types that store multiple values.

    Collections are essential because most real programs work with groups of data:

  • A list of tasks
  • A set of unique tags
  • A dictionary that maps usernames to profiles
  • In this article you will learn:

  • What a collection is and how to choose the right type
  • How to use list, tuple, set, and dict
  • How to add, remove, and look up items
  • How iteration and membership checks work
  • Which common errors appear with collections and how to avoid them
  • What is a collection in Python

    A collection is a value that contains multiple values inside it.

    Key properties that differ between collections:

  • Order: does the collection remember the order of items?
  • Mutability: can you change it after creation?
  • Uniqueness: can it contain duplicates?
  • Lookup style: by position (index) or by key?
  • !A quick comparison of the four collection types and their key properties

    Quick comparison table

    | Type | Literal example | Ordered | Mutable | Duplicates | Access by | |---|---|---|---|---|---| | list | ["a", "b"] | yes | yes | yes | index | | tuple | ("a", "b") | yes | no | yes | index | | set | {"a", "b"} | no | yes | no | item membership | | dict | { "name": "Ana" } | yes | yes | keys unique | key |

    Reference pages (official docs):

  • Python built-in types
  • Built-in functions
  • Lists

    A list stores an ordered sequence of items. You can change it: add, remove, replace elements.

    Creating lists

    Indexing and slicing

    Indexes start at 0.

    A slice takes a part of a list.

    Modifying a list

    Removing:

    Iterating over a list

    You already used for loops. Lists are the most common thing to iterate.

    If you need indexes:

    Membership check

    Common list errors

  • IndexError: index out of range
  • To avoid it, check length:

    Tuples

    A tuple is like a list, but immutable: after creation you can’t change its elements.

    When to use tuples

    Use tuples when:

  • You want a fixed group of values that should not change
  • You want to return multiple values from a function
  • Creating tuples

    Tuple unpacking

    A very common pattern:

    You can also swap variables without a temporary variable:

    What happens if you try to modify a tuple

    That TypeError is a helpful signal: you chose an immutable type.

    Sets

    A set stores unique items. Sets are great for:

  • Removing duplicates
  • Fast membership checks like x in set
  • Basic set operations: union, intersection
  • Creating sets

    Adding and removing

    Membership checks

    Set operations

    Because sets are unordered, you should not rely on element order when printing or iterating.

    Dictionaries

    A dict stores pairs: key → value.

    You use a dictionary when you want to look up data by a meaningful key instead of a numeric index.

    Creating dictionaries

    Reading and writing values

    The KeyError problem and safe access

    If a key does not exist, dict[key] raises KeyError.

    Safe options:

  • in check
  • get() with a default
  • Iterating over dictionaries

    Iterate over keys:

    Iterate over key-value pairs:

    Common dictionary use case: counting

    This pattern combines loops, get(), and assignment.

    Choosing the right collection

    Use this quick guide:

  • Choose a list when you need an ordered, editable sequence
  • Choose a tuple when you need an ordered, fixed sequence
  • Choose a set when you need uniqueness or fast membership checks
  • Choose a dict when you need mapping from keys to values
  • Small example: a simple contacts manager

    This example connects everything you already know: input/output, loops, conditions, functions, and collections.

    Summary

    You now know the four core collection types in Python:

  • list: ordered, mutable, index-based
  • tuple: ordered, immutable, index-based
  • set: unique items, great for membership and deduplication
  • dict: key-value mapping, great for structured data and fast lookups
  • Next, you can combine collections with functions and error handling to build more reliable programs, and later you’ll learn how to work with nested collections like “a list of dictionaries” (very common in practice).

    6. Работа со строками, файлами и форматами данных

    Working with strings, files, and data formats

    In earlier lessons you learned variables and types, control flow (if, loops), functions, and collections (list, dict, set, tuple). Now you will connect these skills to real program input and output: working with text (strings), storing data in files, and exchanging data using common formats like JSON and CSV.

    In this article you will learn:

  • How strings work as sequences (indexing, slicing)
  • Useful string methods for cleaning and parsing input
  • How to format text for output (including f-strings)
  • How to read and write files safely using with open(...)
  • How to work with paths using pathlib
  • How to store structured data with JSON and tabular data with CSV
  • Strings as sequences

    A Python string (str) is an ordered sequence of characters. That means you can do many of the same things you can do with lists:

  • Get length with len(s)
  • Access characters by index s[i]
  • Take slices s[start:stop:step]
  • Iterate with for ch in s
  • Indexing and slicing

    Indexes start at 0. Negative indexes count from the end.

    Common beginner mistake: indexing beyond the end raises IndexError.

    Building and formatting strings

    Concatenation and repetition

    For many pieces, prefer joining (more readable and efficient for lists of parts).

    f-strings

    You already used f-strings; they remain the best default for formatting.

    If you need braces inside an f-string, double them.

    Reference: Formatted string literals (f-strings)

    Escape sequences and multiline strings

    Some characters are written using escapes:

    | Escape | Meaning | |---|---| | \n | newline | | \t | tab | | \\ | backslash | | \" | double quote inside "..." |

    Multiline strings use triple quotes:

    Common string methods for real programs

    String methods help you clean user input and parse text files.

    Cleaning input

    Useful methods:

  • strip() removes whitespace at the ends
  • lower() and upper() normalize case
  • replace(old, new) replaces substrings
  • Reference: String methods

    Checking content

    For validation, you often combine checks with and, or, not from the conditions lesson.

    Splitting and parsing

    split() turns a string into a list.

    Be careful with spaces:

    This uses a list comprehension, which is a compact loop form; if it looks new, read it as: for each part produced by split, strip it, and collect into a list.

    Files: reading and writing text

    Programs often need to save results, read configuration, or process logs. That is file I/O.

    !How file I/O usually works in a Python program

    The with open(...) pattern

    Use with so the file is closed automatically.

    The mode controls what you do:

    | Mode | Meaning | |---|---| | "r" | read | | "w" | write (overwrite) | | "a" | append |

    Write example:

    Reference: Built-in function open

    Reading line by line

    For large files, it is often better to iterate over lines.

    Notes:

  • rstrip("\n") removes only the newline at the end
  • strip() would remove spaces too, which is not always what you want
  • Handling file errors

    If a file does not exist, Python raises FileNotFoundError. You already learned try / except.

    Paths with pathlib

    Hardcoding string paths works, but pathlib makes path operations clearer and more cross-platform.

    Common operations:

    Reference: pathlib — Object-oriented filesystem paths

    Data formats: JSON and CSV

    Text files are great, but real programs often need structured data. Two very common formats are:

  • JSON: nested structures (dicts, lists)
  • CSV: tables (rows and columns)
  • !JSON vs CSV: structured objects vs tabular data

    JSON: saving and loading structured data

    JSON maps naturally to Python collections:

  • JSON object {"a": 1} ↔ Python dict
  • JSON array [1, 2] ↔ Python list
  • JSON string/number/bool/null ↔ Python str/int or float/bool/None
  • #### Writing JSON

    ensure_ascii=False keeps non-ASCII characters readable, and indent=2 makes the file nicely formatted.

    #### Reading JSON

    Reference: json — JSON encoder and decoder

    CSV: saving and loading tabular data

    CSV is a text format where each line is a row and values are separated (often by commas). Do not parse CSV by hand with split(",") for real data, because quoting and commas inside values are common.

    Use the standard csv module.

    #### Writing CSV

    newline="" is recommended by Python docs for correct newline handling.

    #### Reading CSV

    Reference: csv — CSV File Reading and Writing

    Mini-project: persist a todo list in JSON

    This example connects strings, collections, functions, loops, errors, and file formats.

    Goal:

  • Keep a list of tasks in memory
  • Save it to todos.json
  • Load it on startup
  • What to notice:

  • Strings are cleaned with strip()
  • Collections store tasks in memory
  • File I/O is done via JSON and with open(...)
  • Validation uses conditions and loops
  • Summary

    You can now move data in and out of your programs:

  • Strings are sequences, so you can index, slice, and iterate over them
  • String methods like strip(), split(), and join() are essential for parsing
  • Use with open(..., encoding="utf-8") for safe text file I/O
  • Use pathlib to work with file paths cleanly
  • Use JSON for nested structured data and CSV for tables
  • These skills are the foundation for larger practical programs: configuration files, simple databases in JSON, log processing, and importing/exporting spreadsheets.

    7. Модули, пакеты и основы ООП в Python

    Modules, packages, and OOP basics in Python

    In the previous lessons you learned data types, conditions, loops, functions, collections, strings, and file I/O. Now you are ready to structure bigger programs properly.

    Real projects quickly outgrow a single .py file. You need:

  • Modules to split code into files
  • Packages to group modules into folders
  • OOP basics to model data and behavior together (useful for clean program design)
  • This lesson teaches the minimum you need to read and write multi-file Python programs and to understand simple class-based code.

    What is a module

    A module is just a Python file. If you have a file math_tools.py, then the module name is usually math_tools.

    Why modules matter:

  • You can reuse code across files
  • You can keep related functionality together
  • You can avoid very long “everything in one file” scripts
  • Official reference:

  • Python tutorial: Modules
  • Importing modules

    import module

    Here:

  • math is a module from the standard library
  • you access its members with module_name.member
  • from module import name

    This imports a specific name directly into your current file.

    Aliases with as

    Aliases are common when a name is long or when a conventional short name exists.

    What does Python search when you import

    When Python runs import x, it looks for x in a few places. At a beginner level, remember the most practical rules:

  • Python can import modules from the current project folder
  • Python can import installed third-party packages (usually installed into your virtual environment)
  • Python can import the standard library
  • If you see ModuleNotFoundError, it usually means one of these:

  • the file/folder name is wrong
  • you are running the script from a different working directory
  • the package is not installed in the current environment
  • Creating your own module

    Let’s create two files in the same folder:

  • main.py
  • utils.py
  • utils.py:

    main.py:

    Run:

    Key idea:

  • utils.py is a module
  • from utils import read_int imports the function defined in that module
  • __name__ and if __name__ == "__main__"

    When Python runs a file directly, it sets a special variable __name__ to the string "__main__".

    This is used to separate:

  • code that should run only when the file is executed directly
  • code that should not run when the file is imported
  • Example utils.py:

    Behavior:

  • python utils.py prints 5
  • import utils does not print anything (the test code is skipped)
  • Official reference:

  • Python data model: Special attributes
  • What is a package

    A package is a folder that contains Python modules.

    In modern Python, a folder is commonly treated as a package if it is on the import path. Historically, a file named __init__.py was required, and you will still see it in many projects.

    A typical project structure might look like this:

    !A project split into a main script and a package with multiple modules

    Importing from a package

    If your structure is:

  • myapp/utils.py
  • Then in main.py you can write:

    If you instead write from utils import read_int, Python will search for a top-level utils.py next to main.py, which may not exist.

    Official reference:

  • Python tutorial: Packages
  • What __init__.py is for

    __init__.py is a module that runs when the package is imported.

    Common uses:

  • marking the folder as a package (especially in older codebases)
  • exposing a “public API” of the package
  • Example myapp/__init__.py:

    Now this works:

    Note the . in from .utils ...:

  • it means “import from the same package folder”
  • Standard library vs third-party packages

    Standard library

    Python includes many useful modules without any installation:

  • math for math operations
  • pathlib for file paths
  • json for JSON
  • csv for CSV
  • The full list is in the docs:

  • Python standard library
  • Third-party packages and pip

    When you install a library with pip, you add a third-party package into your current environment.

    Best practice from earlier lessons still applies:

  • use a virtual environment (venv)
  • install with python -m pip ...
  • References:

  • pip documentation
  • venv documentation
  • OOP basics: classes and objects

    Why OOP appears in Python

    You can write many scripts using only functions and collections. But OOP becomes helpful when:

  • you want to group data and behavior together
  • you want clear “entities” like User, Task, Invoice
  • you want to make code easier to extend without turning it into a mess of unrelated functions
  • In Python:

  • a class is a blueprint
  • an object (instance) is a concrete value created from that blueprint
  • Official reference:

  • Python tutorial: Classes
  • !Class as a blueprint and objects as created instances

    Defining a class

    A minimal class:

    Creating an object:

    Attributes

    You can attach attributes to objects:

    This works, but is not a great pattern for real projects because you want consistent initialization.

    __init__ and self

    The special method __init__ runs when you create an object.

    Key terms:

  • self is the current object
  • self.name is an attribute stored inside that object
  • Methods

    A method is a function defined inside a class.

    When you call u.greet(), Python passes u as self automatically.

    Class variables vs instance variables

    Instance variables

    Created per object (each instance has its own value):

    Class variables

    Shared by all instances:

    If you update a class variable, it affects all instances that did not override it with an instance attribute.

    A practical OOP example: a TodoList

    This example connects earlier topics (lists, file I/O, JSON, functions) with OOP.

    What to notice:

  • the object todos owns both data (items, path) and behavior (add, remove, load, save)
  • main() stays focused on user interaction
  • you reuse earlier skills (strings, lists, JSON, exceptions), but organize them differently
  • Inheritance in one sentence

    Inheritance lets you create a new class based on another.

    At the beginner stage, the most important idea is:

  • inheritance is mostly used to reuse and customize behavior
  • You do not need to force OOP into every program. Use it when it makes your code simpler to understand.

    Summary

    You learned how to scale your Python code beyond one file:

  • modules are .py files, imported with import ...
  • packages are folders that group modules, often with __init__.py
  • if __name__ == "__main__" protects “run directly” code from executing on import
  • OOP basics: classes, objects, __init__, self, attributes, methods
  • With these tools, you can start building real multi-file projects and read many common Python codebases.