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

index.md

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

1> **Источник:** https://python-all.ru/2.7/tutorial/index.html2>3> «Документация Python на русском» – неофициальный перевод официальной документации Python: версии от 2.6 до 3.16, полнотекстовый поиск, английский оригинал рядом с переводом. Эта Markdown-версия страницы предназначена для работы с LLM: вставьте её в ChatGPT, Claude или Cursor.45---67# Учебник Python89Python – это простой для изучения, но мощный язык программирования. В нём эффективные высокоуровневые структуры данных и простой, но эффективный подход к объектно-ориентированному программированию. Элегантный синтаксис Python, динамическая типизация в сочетании с интерпретируемостью делают его идеальным языком для написания сценариев и быстрой разработки приложений в самых разных областях на большинстве платформ.1011Интерпретатор Python и обширная стандартная библиотека свободно доступны в исходном коде или в двоичном виде для всех основных платформ на веб-сайте Python, [https://www.python.org/](https://python-all.ru/2.7/tutorial/index.html), и могут свободно распространяться. На том же сайте также содержатся дистрибутивы и ссылки на многие бесплатные сторонние модули Python, программы и инструменты, а также дополнительная документация.1213Интерпретатор Python легко расширяется новыми функциями и типами данных, реализованными на C или C++ (или других языках, вызываемых из C). Python также подходит как язык расширения для настраиваемых приложений.1415Этот учебник в неформальной манере знакомит с основными понятиями и особенностями языка Python и его системы. Желательно иметь под рукой интерпретатор Python для получения практического опыта, но все примеры самодостаточны, поэтому учебник можно читать и в автономном режиме.1617Описание стандартных объектов и модулей приведено в [Стандартная библиотека Python](https://python-all.ru/2.7/library/index.html#library-index). [Справочник по языку Python](https://python-all.ru/2.7/reference/index.html#reference-index) содержит более формальное определение языка. Чтобы написать расширения на C или C++, прочитайте [Расширение и встраивание интерпретатора Python](https://python-all.ru/2.7/extending/index.html#extending-index) и [Справочное руководство по Python/C API](https://python-all.ru/2.7/c-api/index.html#c-api-index). Есть также несколько книг, подробно освещающих Python.1819Этот учебник не претендует на полноту и не охватывает каждую отдельную возможность или даже каждую часто используемую возможность. Вместо этого он знакомит со многими наиболее примечательными возможностями Python и даёт хорошее представление о духе и стиле языка. После прочтения вы сможете читать и писать модули и программы на Python и будете готовы узнать больше о различных модулях стандартной библиотеки Python, описанных в [Стандартной библиотеке Python](https://python-all.ru/2.7/library/index.html#library-index).2021[Глоссарий](https://python-all.ru/2.7/glossary.html#glossary) тоже стоит просмотреть.2223- [1. Введение](https://python-all.ru/2.7/tutorial/appetite.html)24- [2. Использование интерпретатора Python](https://python-all.ru/2.7/tutorial/interpreter.html)2526  - [2.1. Запуск интерпретатора](https://python-all.ru/2.7/tutorial/interpreter.html#invoking-the-interpreter)2728    - [2.1.1. Передача аргументов](https://python-all.ru/2.7/tutorial/interpreter.html#argument-passing)29    - [2.1.2. Интерактивный режим](https://python-all.ru/2.7/tutorial/interpreter.html#interactive-mode)30  - [2.2. Интерпретатор и его окружение](https://python-all.ru/2.7/tutorial/interpreter.html#the-interpreter-and-its-environment)3132    - [2.2.1. Кодировка исходного кода](https://python-all.ru/2.7/tutorial/interpreter.html#source-code-encoding)33- [3. Неформальное введение в Python](https://python-all.ru/2.7/tutorial/introduction.html)3435  - [3.1. Использование Python в качестве калькулятора](https://python-all.ru/2.7/tutorial/introduction.html#using-python-as-a-calculator)3637    - [3.1.1. Числа](https://python-all.ru/2.7/tutorial/introduction.html#numbers)38    - [3.1.2. Строки](https://python-all.ru/2.7/tutorial/introduction.html#strings)39    - [3.1.3. Строки Unicode](https://python-all.ru/2.7/tutorial/introduction.html#unicode-strings)40    - [3.1.4. Списки](https://python-all.ru/2.7/tutorial/introduction.html#lists)41  - [3.2. Первые шаги к программированию](https://python-all.ru/2.7/tutorial/introduction.html#first-steps-towards-programming)42- [4. Дополнительные средства управления потоком](https://python-all.ru/2.7/tutorial/controlflow.html)4344  - [4.1. `if` Инструкции](https://python-all.ru/2.7/tutorial/controlflow.html#if-statements)45  - [4.2. `for` Инструкции](https://python-all.ru/2.7/tutorial/controlflow.html#for-statements)46  - [4.3. Функция `range()`](https://python-all.ru/2.7/tutorial/controlflow.html#the-range-function)47  - [4.4. Инструкции `break` и `continue`, а также предложения `else` в циклах](https://python-all.ru/2.7/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops)48  - [4.5. Инструкции `pass`](https://python-all.ru/2.7/tutorial/controlflow.html#pass-statements)49  - [4.6. Определение функций](https://python-all.ru/2.7/tutorial/controlflow.html#defining-functions)50  - [4.7. Подробнее об определении функций](https://python-all.ru/2.7/tutorial/controlflow.html#more-on-defining-functions)5152    - [4.7.1. Значения аргументов по умолчанию](https://python-all.ru/2.7/tutorial/controlflow.html#default-argument-values)53    - [4.7.2. Именованные аргументы](https://python-all.ru/2.7/tutorial/controlflow.html#keyword-arguments)54    - [4.7.3. Произвольные списки аргументов](https://python-all.ru/2.7/tutorial/controlflow.html#arbitrary-argument-lists)55    - [4.7.4. Распаковка списков аргументов](https://python-all.ru/2.7/tutorial/controlflow.html#unpacking-argument-lists)56    - [4.7.5. Лямбда-выражения](https://python-all.ru/2.7/tutorial/controlflow.html#lambda-expressions)57    - [4.7.6. Строки документации](https://python-all.ru/2.7/tutorial/controlflow.html#documentation-strings)58  - [4.8. Интермеццо: стиль кодирования](https://python-all.ru/2.7/tutorial/controlflow.html#intermezzo-coding-style)59- [5. Структуры данных](https://python-all.ru/2.7/tutorial/datastructures.html)6061  - [5.1. Подробнее о списках](https://python-all.ru/2.7/tutorial/datastructures.html#more-on-lists)6263    - [5.1.1. Использование списков как стеков](https://python-all.ru/2.7/tutorial/datastructures.html#using-lists-as-stacks)64    - [5.1.2. Использование списков как очередей](https://python-all.ru/2.7/tutorial/datastructures.html#using-lists-as-queues)65    - [5.1.3. Инструменты функционального программирования](https://python-all.ru/2.7/tutorial/datastructures.html#functional-programming-tools)66    - [5.1.4. Списковые включения](https://python-all.ru/2.7/tutorial/datastructures.html#list-comprehensions)6768      - [5.1.4.1. Вложенные списковые включения](https://python-all.ru/2.7/tutorial/datastructures.html#nested-list-comprehensions)69  - [5.2. Инструкция `del`](https://python-all.ru/2.7/tutorial/datastructures.html#the-del-statement)70  - [5.3. Кортежи и последовательности](https://python-all.ru/2.7/tutorial/datastructures.html#tuples-and-sequences)71  - [5.4. Множества](https://python-all.ru/2.7/tutorial/datastructures.html#sets)72  - [5.5. Словари](https://python-all.ru/2.7/tutorial/datastructures.html#dictionaries)73  - [5.6. Приёмы работы с циклами](https://python-all.ru/2.7/tutorial/datastructures.html#looping-techniques)74  - [5.7. Подробнее об условиях](https://python-all.ru/2.7/tutorial/datastructures.html#more-on-conditions)75  - [5.8. Сравнение последовательностей и других типов](https://python-all.ru/2.7/tutorial/datastructures.html#comparing-sequences-and-other-types)76- [6. Модули](https://python-all.ru/2.7/tutorial/modules.html)7778  - [6.1. Подробнее о модулях](https://python-all.ru/2.7/tutorial/modules.html#more-on-modules)7980    - [6.1.1. Запуск модулей как скриптов](https://python-all.ru/2.7/tutorial/modules.html#executing-modules-as-scripts)81    - [6.1.2. Путь поиска модулей](https://python-all.ru/2.7/tutorial/modules.html#the-module-search-path)82    - [6.1.3. «Скомпилированные» файлы Python](https://python-all.ru/2.7/tutorial/modules.html#compiled-python-files)83  - [6.2. Стандартные модули](https://python-all.ru/2.7/tutorial/modules.html#standard-modules)84  - [6.3. Функция `dir()`](https://python-all.ru/2.7/tutorial/modules.html#the-dir-function)85  - [6.4. Пакеты](https://python-all.ru/2.7/tutorial/modules.html#packages)8687    - [6.4.1. Импорт \* из пакета](https://python-all.ru/2.7/tutorial/modules.html#importing-from-a-package)88    - [6.4.2. Ссылки внутри пакета](https://python-all.ru/2.7/tutorial/modules.html#intra-package-references)89    - [6.4.3. Пакеты в нескольких каталогах](https://python-all.ru/2.7/tutorial/modules.html#packages-in-multiple-directories)90- [7. Ввод и вывод](https://python-all.ru/2.7/tutorial/inputoutput.html)9192  - [7.1. Более сложное форматирование вывода](https://python-all.ru/2.7/tutorial/inputoutput.html#fancier-output-formatting)9394    - [7.1.1. Старое форматирование строк](https://python-all.ru/2.7/tutorial/inputoutput.html#old-string-formatting)95  - [7.2. Чтение и запись файлов](https://python-all.ru/2.7/tutorial/inputoutput.html#reading-and-writing-files)9697    - [7.2.1. Методы файловых объектов](https://python-all.ru/2.7/tutorial/inputoutput.html#methods-of-file-objects)98    - [7.2.2. Сохранение структурированных данных с помощью `json`](https://python-all.ru/2.7/tutorial/inputoutput.html#saving-structured-data-with-json)99- [8. Ошибки и исключения](https://python-all.ru/2.7/tutorial/errors.html)100101  - [8.1. Синтаксические ошибки](https://python-all.ru/2.7/tutorial/errors.html#syntax-errors)102  - [8.2. Исключения](https://python-all.ru/2.7/tutorial/errors.html#exceptions)103  - [8.3. Обработка исключений](https://python-all.ru/2.7/tutorial/errors.html#handling-exceptions)104  - [8.4. Возбуждение исключений](https://python-all.ru/2.7/tutorial/errors.html#raising-exceptions)105  - [8.5. Пользовательские исключения](https://python-all.ru/2.7/tutorial/errors.html#user-defined-exceptions)106  - [8.6. Определение действий по очистке](https://python-all.ru/2.7/tutorial/errors.html#defining-clean-up-actions)107  - [8.7. Предопределённые действия по очистке](https://python-all.ru/2.7/tutorial/errors.html#predefined-clean-up-actions)108- [9. Классы](https://python-all.ru/2.7/tutorial/classes.html)109110  - [9.1. Несколько слов об именах и объектах](https://python-all.ru/2.7/tutorial/classes.html#a-word-about-names-and-objects)111  - [9.2. Области видимости и пространства имён Python](https://python-all.ru/2.7/tutorial/classes.html#python-scopes-and-namespaces)112  - [9.3. Первое знакомство с классами](https://python-all.ru/2.7/tutorial/classes.html#a-first-look-at-classes)113114    - [9.3.1. Синтаксис определения класса](https://python-all.ru/2.7/tutorial/classes.html#class-definition-syntax)115    - [9.3.2. Объекты классов](https://python-all.ru/2.7/tutorial/classes.html#class-objects)116    - [9.3.3. Объекты экземпляров](https://python-all.ru/2.7/tutorial/classes.html#instance-objects)117    - [9.3.4. Объекты методов](https://python-all.ru/2.7/tutorial/classes.html#method-objects)118    - [9.3.5. Переменные класса и экземпляра](https://python-all.ru/2.7/tutorial/classes.html#class-and-instance-variables)119  - [9.4. Разные замечания](https://python-all.ru/2.7/tutorial/classes.html#random-remarks)120  - [9.5. Наследование](https://python-all.ru/2.7/tutorial/classes.html#inheritance)121122    - [9.5.1. Множественное наследование](https://python-all.ru/2.7/tutorial/classes.html#multiple-inheritance)123  - [9.6. Приватные переменные и локальные ссылки класса](https://python-all.ru/2.7/tutorial/classes.html#private-variables-and-class-local-references)124  - [9.7. Разное](https://python-all.ru/2.7/tutorial/classes.html#odds-and-ends)125  - [9.8. Исключения – тоже классы](https://python-all.ru/2.7/tutorial/classes.html#exceptions-are-classes-too)126  - [9.9. Итераторы](https://python-all.ru/2.7/tutorial/classes.html#iterators)127  - [9.10. Генераторы](https://python-all.ru/2.7/tutorial/classes.html#generators)128  - [9.11. Генераторные выражения](https://python-all.ru/2.7/tutorial/classes.html#generator-expressions)129- [10. Краткий обзор стандартной библиотеки](https://python-all.ru/2.7/tutorial/stdlib.html)130131  - [10.1. Интерфейс операционной системы](https://python-all.ru/2.7/tutorial/stdlib.html#operating-system-interface)132  - [10.2. Файловые шаблоны](https://python-all.ru/2.7/tutorial/stdlib.html#file-wildcards)133  - [10.3. Аргументы командной строки](https://python-all.ru/2.7/tutorial/stdlib.html#command-line-arguments)134  - [10.4. Перенаправление вывода ошибок и завершение программы](https://python-all.ru/2.7/tutorial/stdlib.html#error-output-redirection-and-program-termination)135  - [10.5. Поиск по шаблону в строках](https://python-all.ru/2.7/tutorial/stdlib.html#string-pattern-matching)136  - [10.6. Математика](https://python-all.ru/2.7/tutorial/stdlib.html#mathematics)137  - [10.7. Доступ в Интернет](https://python-all.ru/2.7/tutorial/stdlib.html#internet-access)138  - [10.8. Даты и время](https://python-all.ru/2.7/tutorial/stdlib.html#dates-and-times)139  - [10.9. Сжатие данных](https://python-all.ru/2.7/tutorial/stdlib.html#data-compression)140  - [10.10. Измерение производительности](https://python-all.ru/2.7/tutorial/stdlib.html#performance-measurement)141  - [10.11. Контроль качества](https://python-all.ru/2.7/tutorial/stdlib.html#quality-control)142  - [10.12. Батарейки в комплекте](https://python-all.ru/2.7/tutorial/stdlib.html#batteries-included)143- [11. Краткий обзор стандартной библиотеки – Часть II](https://python-all.ru/2.7/tutorial/stdlib2.html)144145  - [11.1. Форматирование вывода](https://python-all.ru/2.7/tutorial/stdlib2.html#output-formatting)146  - [11.2. Шаблоны](https://python-all.ru/2.7/tutorial/stdlib2.html#templating)147  - [11.3. Работа с двоичными данными и структурами записей](https://python-all.ru/2.7/tutorial/stdlib2.html#working-with-binary-data-record-layouts)148  - [11.4. Многопоточность](https://python-all.ru/2.7/tutorial/stdlib2.html#multi-threading)149  - [11.5. Логирование](https://python-all.ru/2.7/tutorial/stdlib2.html#logging)150  - [11.6. Слабые ссылки](https://python-all.ru/2.7/tutorial/stdlib2.html#weak-references)151  - [11.7. Инструменты для работы со списками](https://python-all.ru/2.7/tutorial/stdlib2.html#tools-for-working-with-lists)152  - [11.8. Десятичная арифметика с плавающей запятой](https://python-all.ru/2.7/tutorial/stdlib2.html#decimal-floating-point-arithmetic)153- [12. Что дальше?](https://python-all.ru/2.7/tutorial/whatnow.html)154- [13. Интерактивное редактирование ввода и подстановка истории](https://python-all.ru/2.7/tutorial/interactive.html)155156  - [13.1. Редактирование строк](https://python-all.ru/2.7/tutorial/interactive.html#line-editing)157  - [13.2. Подстановка истории](https://python-all.ru/2.7/tutorial/interactive.html#history-substitution)158  - [13.3. Привязки клавиш](https://python-all.ru/2.7/tutorial/interactive.html#key-bindings)159  - [13.4. Альтернативы интерактивному интерпретатору](https://python-all.ru/2.7/tutorial/interactive.html#alternatives-to-the-interactive-interpreter)160- [14. Арифметика с плавающей запятой: проблемы и ограничения](https://python-all.ru/2.7/tutorial/floatingpoint.html)161162  - [14.1. Ошибка представления](https://python-all.ru/2.7/tutorial/floatingpoint.html#representation-error)163- [15. Приложение](https://python-all.ru/2.7/tutorial/appendix.html)164165  - [15.1. Интерактивный режим](https://python-all.ru/2.7/tutorial/appendix.html#interactive-mode)166167    - [15.1.1. Обработка ошибок](https://python-all.ru/2.7/tutorial/appendix.html#error-handling)168    - [15.1.2. Исполняемые сценарии Python](https://python-all.ru/2.7/tutorial/appendix.html#executable-python-scripts)169    - [15.1.3. Файл интерактивного запуска](https://python-all.ru/2.7/tutorial/appendix.html#the-interactive-startup-file)170    - [15.1.4. Модули настройки](https://python-all.ru/2.7/tutorial/appendix.html#the-customization-modules)171