Документация Python неофициальный перевод

index.md

193 строк · 22.6 КБ · обычная страница · сырой текст · скачать

1> **Источник:** https://python-all.ru/3.15/tutorial/index.html2>3> «Документация Python на русском» – неофициальный перевод официальной документации Python: версии от 2.6 до 3.16, полнотекстовый поиск, английский оригинал рядом с переводом. Эта Markdown-версия страницы предназначена для работы с LLM: вставьте её в ChatGPT, Claude или Cursor.45---67# Учебник Python89> **Совет**10>11> Этот учебник предназначен для *программистов*, которые только начинают знакомство с языком Python, **а не** для *новичков*, которые никогда не программировали.1213Python – это простой для изучения, но мощный язык программирования. В нём эффективные высокоуровневые структуры данных и простой, но эффективный подход к объектно-ориентированному программированию. Элегантный синтаксис Python, динамическая типизация в сочетании с интерпретируемостью делают его идеальным языком для написания сценариев и быстрой разработки приложений в самых разных областях на большинстве платформ.1415Интерпретатор Python и обширная стандартная библиотека свободно доступны в исходном или бинарном виде для всех основных платформ на сайте Python, [https://www.python.org/](https://python-all.ru/3.15/tutorial/index.html), и могут свободно распространяться. Там же можно найти дистрибутивы и ссылки на множество бесплатных сторонних модулей Python, программ, инструментов и дополнительную документацию.1617Интерпретатор Python легко расширяется новыми функциями и типами данных, реализованными на C или C++ (или других языках, вызываемых из C). Python также подходит как язык расширения для настраиваемых приложений.1819Этот учебник неформально знакомит читателя с основными концепциями и возможностями языка и системы Python. Имейте в виду: для изучения предполагается базовое понимание программирования в целом. Полезно иметь под рукой интерпретатор Python для практики, но все примеры самодостаточны, поэтому учебник можно читать и без подключения к сети.2021Описание стандартных объектов и модулей см. в [Стандартной библиотеке Python](https://python-all.ru/3.15/library/index.html#library-index). [Справочник по языку Python](https://python-all.ru/3.15/reference/index.html#reference-index) даёт более формальное определение языка. Для написания расширений на C или C++ читайте [Расширение и встраивание интерпретатора Python](https://python-all.ru/3.15/extending/index.html#extending-index) и [Справочное руководство по Python/C API](https://python-all.ru/3.15/c-api/index.html#c-api-index). Также есть несколько книг, подробно освещающих Python.2223Этот учебник не претендует на полноту и не охватывает каждую отдельную возможность или даже каждую часто используемую возможность. Вместо этого он знакомит со многими наиболее примечательными возможностями Python и даёт хорошее представление о духе и стиле языка. После прочтения вы сможете читать и писать модули и программы на Python и будете готовы узнать больше о различных модулях стандартной библиотеки Python, описанных в [Стандартной библиотеке Python](https://python-all.ru/3.15/library/index.html#library-index).2425[Глоссарий](https://python-all.ru/3.15/glossary.html#glossary) тоже стоит просмотреть.2627- [1. Введение](https://python-all.ru/3.15/tutorial/appetite.html)28- [2. Использование интерпретатора Python](https://python-all.ru/3.15/tutorial/interpreter.html)2930  - [2.1. Запуск интерпретатора](https://python-all.ru/3.15/tutorial/interpreter.html#invoking-the-interpreter)3132    - [2.1.1. Передача аргументов](https://python-all.ru/3.15/tutorial/interpreter.html#argument-passing)33    - [2.1.2. Интерактивный режим](https://python-all.ru/3.15/tutorial/interpreter.html#interactive-mode)34  - [2.2. Интерпретатор и его окружение](https://python-all.ru/3.15/tutorial/interpreter.html#the-interpreter-and-its-environment)3536    - [2.2.1. Кодировка исходного кода](https://python-all.ru/3.15/tutorial/interpreter.html#source-code-encoding)37- [3. Неформальное введение в Python](https://python-all.ru/3.15/tutorial/introduction.html)3839  - [3.1. Использование Python в качестве калькулятора](https://python-all.ru/3.15/tutorial/introduction.html#using-python-as-a-calculator)4041    - [3.1.1. Числа](https://python-all.ru/3.15/tutorial/introduction.html#numbers)42    - [3.1.2. Текст](https://python-all.ru/3.15/tutorial/introduction.html#text)43    - [3.1.3. Списки](https://python-all.ru/3.15/tutorial/introduction.html#lists)44  - [3.2. Первые шаги к программированию](https://python-all.ru/3.15/tutorial/introduction.html#first-steps-towards-programming)45- [4. Дополнительные средства управления потоком](https://python-all.ru/3.15/tutorial/controlflow.html)4647  - [4.1. `if` Инструкции](https://python-all.ru/3.15/tutorial/controlflow.html#if-statements)48  - [4.2. `for` Инструкции](https://python-all.ru/3.15/tutorial/controlflow.html#for-statements)49  - [4.3. Функция `range()`](https://python-all.ru/3.15/tutorial/controlflow.html#the-range-function)50  - [4.4. `break` и `continue` Инструкции](https://python-all.ru/3.15/tutorial/controlflow.html#break-and-continue-statements)51  - [4.5. `else` Предложения в циклах](https://python-all.ru/3.15/tutorial/controlflow.html#else-clauses-on-loops)52  - [4.6. `pass` Инструкции](https://python-all.ru/3.15/tutorial/controlflow.html#pass-statements)53  - [4.7. `match` Инструкции](https://python-all.ru/3.15/tutorial/controlflow.html#match-statements)54  - [4.8. Определение функций](https://python-all.ru/3.15/tutorial/controlflow.html#defining-functions)55  - [4.9. Подробнее об определении функций](https://python-all.ru/3.15/tutorial/controlflow.html#more-on-defining-functions)5657    - [4.9.1. Значения аргументов по умолчанию](https://python-all.ru/3.15/tutorial/controlflow.html#default-argument-values)58    - [4.9.2. Именованные аргументы](https://python-all.ru/3.15/tutorial/controlflow.html#keyword-arguments)59    - [4.9.3. Специальные параметры](https://python-all.ru/3.15/tutorial/controlflow.html#special-parameters)6061      - [4.9.3.1. Позиционно-именованные аргументы](https://python-all.ru/3.15/tutorial/controlflow.html#positional-or-keyword-arguments)62      - [4.9.3.2. Только позиционные параметры](https://python-all.ru/3.15/tutorial/controlflow.html#positional-only-parameters)63      - [4.9.3.3. Только именованные аргументы](https://python-all.ru/3.15/tutorial/controlflow.html#keyword-only-arguments)64      - [4.9.3.4. Примеры функций](https://python-all.ru/3.15/tutorial/controlflow.html#function-examples)65      - [4.9.3.5. Краткий обзор](https://python-all.ru/3.15/tutorial/controlflow.html#recap)66    - [4.9.4. Произвольные списки аргументов](https://python-all.ru/3.15/tutorial/controlflow.html#arbitrary-argument-lists)67    - [4.9.5. Распаковка списков аргументов](https://python-all.ru/3.15/tutorial/controlflow.html#unpacking-argument-lists)68    - [4.9.6. Лямбда-выражения](https://python-all.ru/3.15/tutorial/controlflow.html#lambda-expressions)69    - [4.9.7. Строки документации](https://python-all.ru/3.15/tutorial/controlflow.html#documentation-strings)70    - [4.9.8. Аннотации функций](https://python-all.ru/3.15/tutorial/controlflow.html#function-annotations)71  - [4.10. Интермеццо: стиль кода](https://python-all.ru/3.15/tutorial/controlflow.html#intermezzo-coding-style)72- [5. Структуры данных](https://python-all.ru/3.15/tutorial/datastructures.html)7374  - [5.1. Подробнее о списках](https://python-all.ru/3.15/tutorial/datastructures.html#more-on-lists)7576    - [5.1.1. Использование списков как стеков](https://python-all.ru/3.15/tutorial/datastructures.html#using-lists-as-stacks)77    - [5.1.2. Использование списков как очередей](https://python-all.ru/3.15/tutorial/datastructures.html#using-lists-as-queues)78    - [5.1.3. Списковые включения](https://python-all.ru/3.15/tutorial/datastructures.html#list-comprehensions)79    - [5.1.4. Вложенные списковые включения](https://python-all.ru/3.15/tutorial/datastructures.html#nested-list-comprehensions)80    - [5.1.5. Распаковка в списках и списковых включениях](https://python-all.ru/3.15/tutorial/datastructures.html#unpacking-in-lists-and-list-comprehensions)81  - [5.2. Инструкция `del`](https://python-all.ru/3.15/tutorial/datastructures.html#the-del-statement)82  - [5.3. Кортежи и последовательности](https://python-all.ru/3.15/tutorial/datastructures.html#tuples-and-sequences)83  - [5.4. Множества](https://python-all.ru/3.15/tutorial/datastructures.html#sets)84  - [5.5. Словари](https://python-all.ru/3.15/tutorial/datastructures.html#dictionaries)85  - [5.6. Приёмы работы с циклами](https://python-all.ru/3.15/tutorial/datastructures.html#looping-techniques)86  - [5.7. Подробнее об условиях](https://python-all.ru/3.15/tutorial/datastructures.html#more-on-conditions)87  - [5.8. Сравнение последовательностей и других типов](https://python-all.ru/3.15/tutorial/datastructures.html#comparing-sequences-and-other-types)88- [6. Модули](https://python-all.ru/3.15/tutorial/modules.html)8990  - [6.1. Подробнее о модулях](https://python-all.ru/3.15/tutorial/modules.html#more-on-modules)9192    - [6.1.1. Запуск модулей как скриптов](https://python-all.ru/3.15/tutorial/modules.html#executing-modules-as-scripts)93    - [6.1.2. Путь поиска модулей](https://python-all.ru/3.15/tutorial/modules.html#the-module-search-path)94    - [6.1.3. «Скомпилированные» файлы Python](https://python-all.ru/3.15/tutorial/modules.html#compiled-python-files)95  - [6.2. Стандартные модули](https://python-all.ru/3.15/tutorial/modules.html#standard-modules)96  - [6.3. Функция `dir()`](https://python-all.ru/3.15/tutorial/modules.html#the-dir-function)97  - [6.4. Пакеты](https://python-all.ru/3.15/tutorial/modules.html#packages)9899    - [6.4.1. Импорт \* из пакета](https://python-all.ru/3.15/tutorial/modules.html#importing-from-a-package)100    - [6.4.2. Ссылки внутри пакета](https://python-all.ru/3.15/tutorial/modules.html#intra-package-references)101    - [6.4.3. Пакеты в нескольких каталогах](https://python-all.ru/3.15/tutorial/modules.html#packages-in-multiple-directories)102- [7. Ввод и вывод](https://python-all.ru/3.15/tutorial/inputoutput.html)103104  - [7.1. Более сложное форматирование вывода](https://python-all.ru/3.15/tutorial/inputoutput.html#fancier-output-formatting)105106    - [7.1.1. Форматированные строковые литералы](https://python-all.ru/3.15/tutorial/inputoutput.html#formatted-string-literals)107    - [7.1.2. Метод format() строк](https://python-all.ru/3.15/tutorial/inputoutput.html#the-string-format-method)108    - [7.1.3. Форматирование строк вручную](https://python-all.ru/3.15/tutorial/inputoutput.html#manual-string-formatting)109    - [7.1.4. Устаревшее форматирование строк](https://python-all.ru/3.15/tutorial/inputoutput.html#old-string-formatting)110  - [7.2. Чтение и запись файлов](https://python-all.ru/3.15/tutorial/inputoutput.html#reading-and-writing-files)111112    - [7.2.1. Методы файловых объектов](https://python-all.ru/3.15/tutorial/inputoutput.html#methods-of-file-objects)113    - [7.2.2. Сохранение структурированных данных с помощью `json`](https://python-all.ru/3.15/tutorial/inputoutput.html#saving-structured-data-with-json)114- [8. Ошибки и исключения](https://python-all.ru/3.15/tutorial/errors.html)115116  - [8.1. Синтаксические ошибки](https://python-all.ru/3.15/tutorial/errors.html#syntax-errors)117  - [8.2. Исключения](https://python-all.ru/3.15/tutorial/errors.html#exceptions)118  - [8.3. Обработка исключений](https://python-all.ru/3.15/tutorial/errors.html#handling-exceptions)119  - [8.4. Возбуждение исключений](https://python-all.ru/3.15/tutorial/errors.html#raising-exceptions)120  - [8.5. Цепочки исключений](https://python-all.ru/3.15/tutorial/errors.html#exception-chaining)121  - [8.6. Пользовательские исключения](https://python-all.ru/3.15/tutorial/errors.html#user-defined-exceptions)122  - [8.7. Определение действий по очистке](https://python-all.ru/3.15/tutorial/errors.html#defining-clean-up-actions)123  - [8.8. Предопределённые действия по очистке](https://python-all.ru/3.15/tutorial/errors.html#predefined-clean-up-actions)124  - [8.9. Возбуждение и обработка нескольких несвязанных исключений](https://python-all.ru/3.15/tutorial/errors.html#raising-and-handling-multiple-unrelated-exceptions)125  - [8.10. Обогащение исключений примечаниями](https://python-all.ru/3.15/tutorial/errors.html#enriching-exceptions-with-notes)126- [9. Классы](https://python-all.ru/3.15/tutorial/classes.html)127128  - [9.1. Несколько слов об именах и объектах](https://python-all.ru/3.15/tutorial/classes.html#a-word-about-names-and-objects)129  - [9.2. Области видимости и пространства имён Python](https://python-all.ru/3.15/tutorial/classes.html#python-scopes-and-namespaces)130131    - [9.2.1. Пример областей видимости и пространств имён](https://python-all.ru/3.15/tutorial/classes.html#scopes-and-namespaces-example)132  - [9.3. Первое знакомство с классами](https://python-all.ru/3.15/tutorial/classes.html#a-first-look-at-classes)133134    - [9.3.1. Синтаксис определения класса](https://python-all.ru/3.15/tutorial/classes.html#class-definition-syntax)135    - [9.3.2. Объекты классов](https://python-all.ru/3.15/tutorial/classes.html#class-objects)136    - [9.3.3. Объекты экземпляров](https://python-all.ru/3.15/tutorial/classes.html#instance-objects)137    - [9.3.4. Объекты методов](https://python-all.ru/3.15/tutorial/classes.html#method-objects)138    - [9.3.5. Переменные класса и экземпляра](https://python-all.ru/3.15/tutorial/classes.html#class-and-instance-variables)139  - [9.4. Разные замечания](https://python-all.ru/3.15/tutorial/classes.html#random-remarks)140  - [9.5. Наследование](https://python-all.ru/3.15/tutorial/classes.html#inheritance)141142    - [9.5.1. Множественное наследование](https://python-all.ru/3.15/tutorial/classes.html#multiple-inheritance)143  - [9.6. Приватные переменные](https://python-all.ru/3.15/tutorial/classes.html#private-variables)144  - [9.7. Разное](https://python-all.ru/3.15/tutorial/classes.html#odds-and-ends)145  - [9.8. Итераторы](https://python-all.ru/3.15/tutorial/classes.html#iterators)146  - [9.9. Генераторы](https://python-all.ru/3.15/tutorial/classes.html#generators)147  - [9.10. Генераторные выражения](https://python-all.ru/3.15/tutorial/classes.html#generator-expressions)148- [10. Краткий обзор стандартной библиотеки](https://python-all.ru/3.15/tutorial/stdlib.html)149150  - [10.1. Интерфейс операционной системы](https://python-all.ru/3.15/tutorial/stdlib.html#operating-system-interface)151  - [10.2. Шаблоны имён файлов](https://python-all.ru/3.15/tutorial/stdlib.html#file-wildcards)152  - [10.3. Аргументы командной строки](https://python-all.ru/3.15/tutorial/stdlib.html#command-line-arguments)153  - [10.4. Перенаправление вывода ошибок и завершение программы](https://python-all.ru/3.15/tutorial/stdlib.html#error-output-redirection-and-program-termination)154  - [10.5. Сопоставление строк с шаблоном](https://python-all.ru/3.15/tutorial/stdlib.html#string-pattern-matching)155  - [10.6. Математика](https://python-all.ru/3.15/tutorial/stdlib.html#mathematics)156  - [10.7. Доступ к Интернету](https://python-all.ru/3.15/tutorial/stdlib.html#internet-access)157  - [10.8. Дата и время](https://python-all.ru/3.15/tutorial/stdlib.html#dates-and-times)158  - [10.9. Сжатие данных](https://python-all.ru/3.15/tutorial/stdlib.html#data-compression)159  - [10.10. Измерение производительности](https://python-all.ru/3.15/tutorial/stdlib.html#performance-measurement)160  - [10.11. Контроль качества](https://python-all.ru/3.15/tutorial/stdlib.html#quality-control)161  - [10.12. «Батарейки в комплекте»](https://python-all.ru/3.15/tutorial/stdlib.html#batteries-included)162- [11. Краткий обзор стандартной библиотеки. Часть II](https://python-all.ru/3.15/tutorial/stdlib2.html)163164  - [11.1. Форматирование вывода](https://python-all.ru/3.15/tutorial/stdlib2.html#output-formatting)165  - [11.2. Шаблоны](https://python-all.ru/3.15/tutorial/stdlib2.html#templating)166  - [11.3. Работа с двоичными данными и структурами записей](https://python-all.ru/3.15/tutorial/stdlib2.html#working-with-binary-data-record-layouts)167  - [11.4. Многопоточность](https://python-all.ru/3.15/tutorial/stdlib2.html#multi-threading)168  - [11.5. Логирование](https://python-all.ru/3.15/tutorial/stdlib2.html#logging)169  - [11.6. Слабые ссылки](https://python-all.ru/3.15/tutorial/stdlib2.html#weak-references)170  - [11.7. Инструменты для работы со списками](https://python-all.ru/3.15/tutorial/stdlib2.html#tools-for-working-with-lists)171  - [11.8. Десятичная арифметика с плавающей запятой](https://python-all.ru/3.15/tutorial/stdlib2.html#decimal-floating-point-arithmetic)172- [12. Виртуальные окружения и пакеты](https://python-all.ru/3.15/tutorial/venv.html)173174  - [12.1. Введение](https://python-all.ru/3.15/tutorial/venv.html#introduction)175  - [12.2. Создание виртуальных окружений](https://python-all.ru/3.15/tutorial/venv.html#creating-virtual-environments)176  - [12.3. Управление пакетами с помощью pip](https://python-all.ru/3.15/tutorial/venv.html#managing-packages-with-pip)177- [13. Что дальше?](https://python-all.ru/3.15/tutorial/whatnow.html)178- [14. Интерактивное редактирование ввода и подстановка истории](https://python-all.ru/3.15/tutorial/interactive.html)179180  - [14.1. Автодополнение по табуляции и редактирование истории](https://python-all.ru/3.15/tutorial/interactive.html#tab-completion-and-history-editing)181  - [14.2. Альтернативы интерактивному интерпретатору](https://python-all.ru/3.15/tutorial/interactive.html#alternatives-to-the-interactive-interpreter)182- [15. Арифметика с плавающей запятой: проблемы и ограничения](https://python-all.ru/3.15/tutorial/floatingpoint.html)183184  - [15.1. Ошибка представления](https://python-all.ru/3.15/tutorial/floatingpoint.html#representation-error)185- [16. Приложение](https://python-all.ru/3.15/tutorial/appendix.html)186187  - [16.1. Интерактивный режим](https://python-all.ru/3.15/tutorial/appendix.html#interactive-mode)188189    - [16.1.1. Обработка ошибок](https://python-all.ru/3.15/tutorial/appendix.html#error-handling)190    - [16.1.2. Исполняемые скрипты Python](https://python-all.ru/3.15/tutorial/appendix.html#executable-python-scripts)191    - [16.1.3. Файл автозагрузки интерактивного режима](https://python-all.ru/3.15/tutorial/appendix.html#the-interactive-startup-file)192    - [16.1.4. Модули настройки](https://python-all.ru/3.15/tutorial/appendix.html#the-customization-modules)193