1. Introduction¶
This reference manual describes the Python programming language. It is not intended as a tutorial.
While I am trying to be as precise as possible, I chose to use English rather than formal specifications for everything except syntax and lexical analysis. This should make the document more understandable to the average reader, but will leave room for ambiguities. Consequently, if you were coming from Mars and tried to re-implement Python from this document alone, you might have to guess things and in fact you would probably end up implementing quite a different language. On the other hand, if you are using Python and wonder what the precise rules about a particular area of the language are, you should definitely be able to find them here. If you would like to see a more formal definition of the language, maybe you could volunteer your time — or invent a cloning machine :-).
It is dangerous to add too many implementation details to a language reference document — the implementation may change, and other implementations of the same language may work differently. On the other hand, CPython is the one Python implementation in widespread use (although alternate implementations continue to gain support), and its particular quirks are sometimes worth being mentioned, especially where the implementation imposes additional limitations. Therefore, you’ll find short “implementation notes” sprinkled throughout the text.
Every Python implementation comes with a number of built-in and standard modules. These are documented in The Python Standard Library . A few built-in modules are mentioned when they interact in a significant way with the language definition.
1.1. Alternate Implementations¶
Though there is one Python implementation which is by far the most popular, there are some alternate implementations which are of particular interest to different audiences.
Known implementations include:
This is the original and most-maintained implementation of Python, written in C. New language features generally appear here first.
Python implemented in Java. This implementation can be used as a scripting language for Java applications, or can be used to create applications using the Java class libraries. It is also often used to create tests for Java libraries. More information can be found at the Jython website.
This implementation actually uses the CPython implementation, but is a managed .NET application and makes .NET libraries available. It was created by Brian Lloyd. For more information, see the Python for .NET home page.
An alternate Python for .NET. Unlike Python.NET, this is a complete Python implementation that generates IL, and compiles Python code directly to .NET assemblies. It was created by Jim Hugunin, the original creator of Jython. For more information, see the IronPython website.
An implementation of Python written completely in Python. It supports several advanced features not found in other implementations like stackless support and a Just in Time compiler. One of the goals of the project is to encourage experimentation with the language itself by making it easier to modify the interpreter (since it is written in Python). Additional information is available on the PyPy project’s home page.
Each of these implementations varies in some way from the language as documented in this manual, or introduces specific information beyond what’s covered in the standard Python documentation. Please refer to the implementation-specific documentation to determine what else you need to know about the specific implementation you’re using.
1.2. Notation¶
The descriptions of lexical analysis and syntax use a modified BNF grammar notation. This uses the following style of definition:
name ::=lc_letter
(lc_letter
| "_")* lc_letter ::= "a". "z"
The first line says that a name is an lc_letter followed by a sequence of zero or more lc_letter s and underscores. An lc_letter in turn is any of the single characters ‘a’ through ‘z’ . (This rule is actually adhered to for the names defined in lexical and grammar rules in this document.)
Each rule begins with a name (which is the name defined by the rule) and ::= . A vertical bar ( | ) is used to separate alternatives; it is the least binding operator in this notation. A star ( * ) means zero or more repetitions of the preceding item; likewise, a plus ( + ) means one or more repetitions, and a phrase enclosed in square brackets ( [ ] ) means zero or one occurrences (in other words, the enclosed phrase is optional). The * and + operators bind as tightly as possible; parentheses are used for grouping. Literal strings are enclosed in quotes. White space is only meaningful to separate tokens. Rules are normally contained on a single line; rules with many alternatives may be formatted alternatively with each line after the first beginning with a vertical bar.
In lexical definitions (as the example above), two more conventions are used: Two literal characters separated by three dots mean a choice of any single character in the given (inclusive) range of ASCII characters. A phrase between angular brackets ( <. >) gives an informal description of the symbol defined; e.g., this could be used to describe the notion of ‘control character’ if needed.
Even though the notation used is almost the same, there is a big difference between the meaning of lexical and syntactic definitions: a lexical definition operates on the individual characters of the input source, while a syntax definition operates on the stream of tokens generated by the lexical analysis. All uses of BNF in the next chapter (“Lexical Analysis”) are lexical definitions; uses in subsequent chapters are syntactic definitions.
Язык Python — описание, синтаксис, плюсы и минусы
Python — высокоуровневый язык программирования общего назначения. Он имеет минималистичный синтаксис и направлен на повышение читаемости кода (и в целом на повышение производительности разработчика).
В статье рассмотрим основные особенности языка, его плюсы и минусы, базовый синтаксис + разберём простой пример кода.
О языке
По-русски Python произносится как — «пайтон», но более распространенная версия произношения — «питон». Язык поддерживает несколько парадигм программирования: объектно-ориентированное, функциональное, структурное, императивное и аспектно-ориентированное.
Основная реализация языка Python — CPython . Написана на C .
История создания
Разработку Python начал Гвидо ван Россум в декабре 1989 года. Для ОС Amoeba требовался расширяемый скриптовый язык. На досуге, Гвидо начал писать Python, позаимствовав некоторые наработки из языка ABC.
Версия Python 2.0 была выпущена 16 октября 2000 г., а первая обратно-несовместимая версия Python 3.0 — 3 декабря 2008 г.
Какие задачи удобно решать на Python
Основной упор в Python делается на скорости написания кода (а не на скорости выполнения кода, как например в языках С и C++). Поэтому в первую очередь Python удобно использовать там, где нужно быстро написать что-то работающее.
Все чаще Python используется для анализа данных, как в науке, так и коммерческой сфере. Этому способствует простота языка и большое разнообразие открытых библиотек.
Другая область применения, для которой хорош Питон — системное администрирование и DevOps. На это есть как минимум 3 причины:
- благодаря своей простоте, системному администратору не так сложно выучить этот язык и начать им пользоваться;
- огромный выбор библиотек;
- python входит в состав большинства дистрибутивов Linux.
Типизация
Python является языком с полной динамической типизацией и автоматическим управлением памятью. Динамическая типизация означает, что тип переменной определяется только во время исполнения.
С одной стороны, динамическая типизация упрощает написание программ. Но с другой, имеет ряд недостатков — повышается риск ошибиться с типами и снижается производительность программы.
В «Питоне» реализованы встроенные типы, например:
- булевый тип;
- строка;
- целое число произвольной точности;
- число с плавающей запятой;
- комплексное число.
Также есть и готовые коллекции:
Добавить новый тип можно написав свой класс или определив новый тип в модуле расширения.
Производительность
По производительности Python относительно медленный язык (по сравнению с C, Go, Java). Его скорость выполнения схожа с другими интерпретируемыми языками (PHP, Ruby). Однако возможность компиляции python-кода в байт-код позволяет добиться большей производительности.
Основные причины, из-за которых Python «медленный»:
- GIL (глобальная блокировка интерпретатора).
- Динамическая типизация.
- Python это интерпретируемый, а не компилируемый язык.
Несмотря на это, в большинстве задач гораздо важнее быстро получить результат, нежели ускорить выполнение программы. Особенно это важно для бизнеса или стартапа, где критически важно быстро выпустить продукт в production и начать зарабатывать.
Если для задачи критична производительность, используйте последнюю версию Python. Или присмотритесь к PyPy.
GIL
Global Interpreter Lock — это глобальная блокировка интерпретатора Python. GIL накладывает ограничение на потоки — нельзя использовать несколько процессоров одновременно. Тем самым GIL помогает избежать конфликтов при одновременном обращении разных потоков к одним и тем же участкам памяти.
Многие разработчики против GIL в Python-е, однако создатель проекта Гвидо ван Россум заявляет, что GIL не так уж и плох, и убирать его из CPython`а он не планирует.
Плюсы и минусы Python
- низкий порог вхождения;
- язык широкого применения;
- минималистичный синтаксис;
- кроссплатформенность;
- открытый исходный код интерпретатора CPython;
- наличие дружелюбного, отзывчивого сообщества;
- поддержка многих IDE;
- огромное количество библиотек;
- входит в поставку большинства дистрибутивов Linux.
Синтаксис
Программный код на Python организовывается в функции и классы. Они объединяются в модули, а модули могут быть объединены в пакеты.
Синтаксис Python прост и лаконичен, что делает его удобным для изучения.
Отличительная черта языка — использование отступов для выделения блоков кода и управляющих структур
В отличие от других языков программирования, отступы в Python напрямую влияют на вложенность выражений. Именно эта особенность положительно влияет на читаемость Python-кода.
Пример кода
Простой пример кода — классический «Hello, World!»:
Попробуем разобрать более сложный код. Дано: 10 рандомных чисел. Необходимо отсортировать их в порядке возрастания.
from random import randint def get_numbers(count): numbers = [] for i in range(count): numbers.append(randint(1, 99)) return numbers my_numbers = get_numbers(10) my_numbers.sort() print(my_numbers)
- В первой строке мы импортируем функцию randint из модуля random . Эта функция нужна нам для генерации случайных целых чисел (модуль random входит в стандартную библиотеку Python, отдельно его устанавливать не нужно).
- get_numbers — это функция. Об этом говорит инструкция def В круглых скобках находится аргумент этой функции — count .
- Инструкцией get_numbers(10) мы вызываем функцию. Аргумент count теперь равен 10. Count в нашем случае это количество чисел, которое мы хотим сгенерировать.
- Инструкция for i in range(count) — это цикл (перебор). В нашем случае от 0 до 9.
- randint(1, 99) вернет рандомное (случайное) число от 1 до 99.
- Метод append добавит рандомное число в список numbers .
- И так 10 раз.
- Когда цикл закончится, функция вернет список из 10-ти рандомных чисел. Этот список мы присвоим переменной my_numbers .
- Далее вызовем метод sort который отсортирует список по возрастанию.
- А функция print выведет наш отсортированный список на экран (в консоль).
Результат выполнения данного скрипта выглядит следующим образом:
[20, 27, 29, 36, 53, 74, 75, 81, 87, 93]В данной статье мы рассмотрели лишь верхушку айсберга под названием Python. Изучив этот язык вы удивитесь, насколько просто и лаконично может выглядеть код и как просто его писать.