2. Lexical analysis¶
A Python program is read by a parser. Input to the parser is a stream of tokens, generated by the lexical analyzer. This chapter describes how the lexical analyzer breaks a file into tokens.
Python reads program text as Unicode code points; the encoding of a source file can be given by an encoding declaration and defaults to UTF-8, see PEP 3120 for details. If the source file cannot be decoded, a SyntaxError is raised.
2.1. Line structure¶
A Python program is divided into a number of logical lines.
2.1.1. Logical lines¶
The end of a logical line is represented by the token NEWLINE. Statements cannot cross logical line boundaries except where NEWLINE is allowed by the syntax (e.g., between statements in compound statements). A logical line is constructed from one or more physical lines by following the explicit or implicit line joining rules.
2.1.2. Physical lines¶
A physical line is a sequence of characters terminated by an end-of-line sequence. In source files and strings, any of the standard platform line termination sequences can be used — the Unix form using ASCII LF (linefeed), the Windows form using the ASCII sequence CR LF (return followed by linefeed), or the old Macintosh form using the ASCII CR (return) character. All of these forms can be used equally, regardless of platform. The end of input also serves as an implicit terminator for the final physical line.
When embedding Python, source code strings should be passed to Python APIs using the standard C conventions for newline characters (the \n character, representing ASCII LF, is the line terminator).
2.1.3. Comments¶
A comment starts with a hash character ( # ) that is not part of a string literal, and ends at the end of the physical line. A comment signifies the end of the logical line unless the implicit line joining rules are invoked. Comments are ignored by the syntax.
2.1.4. Encoding declarations¶
If a comment in the first or second line of the Python script matches the regular expression coding[=:]\s*([-\w.]+) , this comment is processed as an encoding declaration; the first group of this expression names the encoding of the source code file. The encoding declaration must appear on a line of its own. If it is the second line, the first line must also be a comment-only line. The recommended forms of an encoding expression are
which is recognized also by GNU Emacs, and
which is recognized by Bram Moolenaar’s VIM.
If no encoding declaration is found, the default encoding is UTF-8. In addition, if the first bytes of the file are the UTF-8 byte-order mark ( b’\xef\xbb\xbf’ ), the declared file encoding is UTF-8 (this is supported, among others, by Microsoft’s notepad).
If an encoding is declared, the encoding name must be recognized by Python (see Standard Encodings ). The encoding is used for all lexical analysis, including string literals, comments and identifiers.
2.1.5. Explicit line joining¶
Two or more physical lines may be joined into logical lines using backslash characters ( \ ), as follows: when a physical line ends in a backslash that is not part of a string literal or comment, it is joined with the following forming a single logical line, deleting the backslash and the following end-of-line character. For example:
A line ending in a backslash cannot carry a comment. A backslash does not continue a comment. A backslash does not continue a token except for string literals (i.e., tokens other than string literals cannot be split across physical lines using a backslash). A backslash is illegal elsewhere on a line outside a string literal.
2.1.6. Implicit line joining¶
Expressions in parentheses, square brackets or curly braces can be split over more than one physical line without using backslashes. For example:
Implicitly continued lines can carry comments. The indentation of the continuation lines is not important. Blank continuation lines are allowed. There is no NEWLINE token between implicit continuation lines. Implicitly continued lines can also occur within triple-quoted strings (see below); in that case they cannot carry comments.
2.1.7. Blank lines¶
A logical line that contains only spaces, tabs, formfeeds and possibly a comment, is ignored (i.e., no NEWLINE token is generated). During interactive input of statements, handling of a blank line may differ depending on the implementation of the read-eval-print loop. In the standard interactive interpreter, an entirely blank logical line (i.e. one containing not even whitespace or a comment) terminates a multi-line statement.
2.1.8. Indentation¶
Leading whitespace (spaces and tabs) at the beginning of a logical line is used to compute the indentation level of the line, which in turn is used to determine the grouping of statements.
Tabs are replaced (from left to right) by one to eight spaces such that the total number of characters up to and including the replacement is a multiple of eight (this is intended to be the same rule as used by Unix). The total number of spaces preceding the first non-blank character then determines the line’s indentation. Indentation cannot be split over multiple physical lines using backslashes; the whitespace up to the first backslash determines the indentation.
Indentation is rejected as inconsistent if a source file mixes tabs and spaces in a way that makes the meaning dependent on the worth of a tab in spaces; a TabError is raised in that case.
Cross-platform compatibility note: because of the nature of text editors on non-UNIX platforms, it is unwise to use a mixture of spaces and tabs for the indentation in a single source file. It should also be noted that different platforms may explicitly limit the maximum indentation level.
A formfeed character may be present at the start of the line; it will be ignored for the indentation calculations above. Formfeed characters occurring elsewhere in the leading whitespace have an undefined effect (for instance, they may reset the space count to zero).
The indentation levels of consecutive lines are used to generate INDENT and DEDENT tokens, using a stack, as follows.
Before the first line of the file is read, a single zero is pushed on the stack; this will never be popped off again. The numbers pushed on the stack will always be strictly increasing from bottom to top. At the beginning of each logical line, the line’s indentation level is compared to the top of the stack. If it is equal, nothing happens. If it is larger, it is pushed on the stack, and one INDENT token is generated. If it is smaller, it must be one of the numbers occurring on the stack; all numbers on the stack that are larger are popped off, and for each number popped off a DEDENT token is generated. At the end of the file, a DEDENT token is generated for each number remaining on the stack that is larger than zero.
Here is an example of a correctly (though confusingly) indented piece of Python code:
The following example shows various indentation errors:
(Actually, the first three errors are detected by the parser; only the last error is found by the lexical analyzer — the indentation of return r does not match a level popped off the stack.)
2.1.9. Whitespace between tokens¶
Except at the beginning of a logical line or in string literals, the whitespace characters space, tab and formfeed can be used interchangeably to separate tokens. Whitespace is needed between two tokens only if their concatenation could otherwise be interpreted as a different token (e.g., ab is one token, but a b is two tokens).
2.2. Other tokens¶
Besides NEWLINE, INDENT and DEDENT, the following categories of tokens exist: identifiers, keywords, literals, operators, and delimiters. Whitespace characters (other than line terminators, discussed earlier) are not tokens, but serve to delimit tokens. Where ambiguity exists, a token comprises the longest possible string that forms a legal token, when read from left to right.
2.3. Identifiers and keywords¶
Identifiers (also referred to as names) are described by the following lexical definitions.
The syntax of identifiers in Python is based on the Unicode standard annex UAX-31, with elaboration and changes as defined below; see also PEP 3131 for further details.
Within the ASCII range (U+0001..U+007F), the valid characters for identifiers are the same as in Python 2.x: the uppercase and lowercase letters A through Z , the underscore _ and, except for the first character, the digits 0 through 9 .
Python 3.0 introduces additional characters from outside the ASCII range (see PEP 3131). For these characters, the classification uses the version of the Unicode Character Database as included in the unicodedata module.
Identifiers are unlimited in length. Case is significant.
The Unicode category codes mentioned above stand for:
Lu — uppercase letters
Ll — lowercase letters
Lt — titlecase letters
Lm — modifier letters
Lo — other letters
Nl — letter numbers
Mn — nonspacing marks
Mc — spacing combining marks
Nd — decimal numbers
Pc — connector punctuations
Other_ID_Start — explicit list of characters in PropList.txt to support backwards compatibility
All identifiers are converted into the normal form NFKC while parsing; comparison of identifiers is based on NFKC.
A non-normative HTML file listing all valid identifier characters for Unicode 14.0.0 can be found at https://www.unicode.org/Public/14.0.0/ucd/DerivedCoreProperties.txt
2.3.1. Keywords¶
The following identifiers are used as reserved words, or keywords of the language, and cannot be used as ordinary identifiers. They must be spelled exactly as written here:
2.3.2. Soft Keywords¶
New in version 3.10.
Some identifiers are only reserved under specific contexts. These are known as soft keywords. The identifiers match , case and _ can syntactically act as keywords in contexts related to the pattern matching statement, but this distinction is done at the parser level, not when tokenizing.
As soft keywords, their use with pattern matching is possible while still preserving compatibility with existing code that uses match , case and _ as identifier names.
2.3.3. Reserved classes of identifiers¶
Certain classes of identifiers (besides keywords) have special meanings. These classes are identified by the patterns of leading and trailing underscore characters:
Not imported by from module import * .
In a case pattern within a match statement, _ is a soft keyword that denotes a wildcard .
Separately, the interactive interpreter makes the result of the last evaluation available in the variable _ . (It is stored in the builtins module, alongside built-in functions like print .)
Elsewhere, _ is a regular identifier. It is often used to name “special” items, but it is not special to Python itself.
The name _ is often used in conjunction with internationalization; refer to the documentation for the gettext module for more information on this convention.
It is also commonly used for unused variables.
System-defined names, informally known as “dunder” names. These names are defined by the interpreter and its implementation (including the standard library). Current system names are discussed in the Special method names section and elsewhere. More will likely be defined in future versions of Python. Any use of __*__ names, in any context, that does not follow explicitly documented use, is subject to breakage without warning.
Class-private names. Names in this category, when used within the context of a class definition, are re-written to use a mangled form to help avoid name clashes between “private” attributes of base and derived classes. See section Identifiers (Names) .
2.4. Literals¶
Literals are notations for constant values of some built-in types.
2.4.1. String and Bytes literals¶
String literals are described by the following lexical definitions:
One syntactic restriction not indicated by these productions is that whitespace is not allowed between the stringprefix or bytesprefix and the rest of the literal. The source character set is defined by the encoding declaration; it is UTF-8 if no encoding declaration is given in the source file; see section Encoding declarations .
In plain English: Both types of literals can be enclosed in matching single quotes ( ‘ ) or double quotes ( " ). They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as triple-quoted strings). The backslash ( \ ) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.
Bytes literals are always prefixed with ‘b’ or ‘B’ ; they produce an instance of the bytes type instead of the str type. They may only contain ASCII characters; bytes with a numeric value of 128 or greater must be expressed with escapes.
Both string and bytes literals may optionally be prefixed with a letter ‘r’ or ‘R’ ; such strings are called raw strings and treat backslashes as literal characters. As a result, in string literals, ‘\U’ and ‘\u’ escapes in raw strings are not treated specially. Given that Python 2.x’s raw unicode literals behave differently than Python 3.x’s the ‘ur’ syntax is not supported.
New in version 3.3: The ‘rb’ prefix of raw bytes literals has been added as a synonym of ‘br’ .
New in version 3.3: Support for the unicode legacy literal ( u’value’ ) was reintroduced to simplify the maintenance of dual Python 2.x and 3.x codebases. See PEP 414 for more information.
A string literal with ‘f’ or ‘F’ in its prefix is a formatted string literal; see Formatted string literals . The ‘f’ may be combined with ‘r’ , but not with ‘b’ or ‘u’ , therefore raw formatted strings are possible, but formatted bytes literals are not.
In triple-quoted literals, unescaped newlines and quotes are allowed (and are retained), except that three unescaped quotes in a row terminate the literal. (A “quote” is the character used to open the literal, i.e. either ‘ or " .)
Unless an ‘r’ or ‘R’ prefix is present, escape sequences in string and bytes literals are interpreted according to rules similar to those used by Standard C. The recognized escape sequences are:
How To Print A Tab In Python
The easiest way to print a tab character in Python is to use the short-hand abbreviation ‘\t’ . To see the tab spaced character in the REPL wrap any variable containing a tab character in the built-in print() function.
Here’s a simple example:
What if you’d prefer to see the tab character instead of the actual spacing?
If in the REPL just return the variable containing the tabbed string on a new line, like so:
You can use the shortcut form of the tab character in most places, but you cannot use any backslash character in an f-string expression (the commands between the curly braces <> .
For example, using the following produces a SyntaxError :
There are a couple of ways to get around this limitation (besides not using slashes at all!).
As demonstrated in the post where I use tabs to print a list, you can place the tab character into a variable and reference the “tab variable” in the f-string expression, like so:
Using chr() Built-In Function
An alternative approach to the shorthand method is using the built-in chr() function.
The chr() function takes one parameter, an integer ranging from 0 to 1,114,111, with each number in that range representing a Unicode character.
To find out what the integer representation of the tab character is, you can use another built-in function ord() which provides the integer representation of a Unicode character. Using it and confirming like so:
As you can see chr(9) represents the tab character. Therefore, another way to print the tab character is to use the chr(9) function as this produces the same results:
Summary
To print the tab character use the abbreviated shorthand method of ‘\t’ or chr(9) if using backslashes in your context will not work.
Next, you might want to read another post about how many spaces is a tab?
Основы программирования на языке Python. Часть 2
В первой части «Основы программирования на языке Python. Часть 1» мы научились создавать самый простой мир, в котором живут разные человечки со своими особенностями, но без особых целей в жизни.
Пора заставить их что-то делать и использовать свой потенциал по максимуму.
Условная конструкция. Табуляция
В этой статье мы будем переводить с алгоритмического языка на язык Python то, что выучили в одной из предыдущих статей про алгоритмы. Подробнее об этом читаем в статье «Основы алгоритмов». Также мы успели изучить создание и применение переменных в Python, и то, какие типы данных могут быть им присвоены в статье «Основы программирования на языке Python. Часть 1». Но далеко на этом не уедешь — нет никакой гибкости, никаких дополнительных возможностей, ничего интересного.
Условная конструкция if-elif-else — первый шаг на пути к разнообразию. Ее цель — совершать конкретные действия при конкретных обстоятельствах.
Это та самая конструкция, которая помогала нам поперчить супчик только в том случае, если мы любим перец. Мы задаем какое-то условие, и если оно выполняется, срабатывает определенная команда или набор команд, а если нет — выполняется другая команда или не происходит ничего.
Как в программе Python выглядят ветвления?
Подробно разберем строение этой конструкции:
- if — главная команда создания условия, ее одной уже достаточно. С ней конструкция будет выглядеть так:
Если <условие> выполнится, то будет запущено <тело условия>, иначе не произойдет ничего.
- else — команда, задающая альтернативу.
Если <условие> выполнится, то будет запущен блок <тело условия 1>, а если оно не выполнится — запустится <тело условия 2>.
- elif — команда для создания сложного условия, когда у нас есть не два исхода, а больше.
В зависимости от выполнения какого-то из <условий> будет запущено соответствующее <тело условия>. Команда else в данном случае не обязательна: если она есть, при невыполнении всех условий выполнится ее тело, а если ее нет — просто не произойдет ничего.
Для записи условий в Python предусмотрены как математические операторы сравнения, так и логические операторы:
Математические операторы сравнения:
- Больше «>»
- Больше или равно «>=»
- Меньше «<«
- Меньше или равно «<=»
- Равно «==»
- Не равно «!=»
Логические операторы:
- Конъюнкция «and»
- Дизъюнкция «or»
- Отрицание «not»
- Эквиваленция «==»
- Импликация «<=»
Подробнее про логические операторы можно узнать в статье «Алгебра логики».
Причем если мы попробуем вывести на экран результат выполнения этих условий, мы увидим, что они могут вернуть:
- либо значение True (которое соответствует выполнению записанного условия),
- либо False (соответствующее невыполнению условия).
Это как раз и есть тот самый тип данных bool из предыдущей части.
Табуляцию можно проставить либо нажатием клавиши Tab, либо используя несколько идущих подряд пробелов (традиционно табуляции соответствует 4 пробела). Но нельзя одновременно использовать и пробелы, и Tab — в одном блоке должно быть только что-то одно.
Про табуляцию вообще нельзя забывать и нужно быть с ней аккуратнее:
- если ее проставить неправильно — программа будет выполняться не так, как мы задумали;
- если не проставить совсем — программа не сможет даже запуститься.
В примере ниже ни одна из переменных не изменится, потому что оба изменения их значений находятся в условии, которое не выполнилось. Но их значения все равно будут выведены на экран, так как вывод идет уже после тела условия.
Ниже изменение переменной х уже не входит в тело условия, так как его табуляция стала на 1 меньше, чем у тела условия. Команда изменения переменной х вернулась в основной блок кода, поэтому она выполняется. Изменение переменной у все еще не происходит, так как оно находится в теле невыполняющегося условия.
Приведенный ниже код не выведет вообще ничего, так как теперь в тело условия, которое не выполняется, попадает и сама команда print.
Циклы. Тип range
Как в программе Python выглядят циклы?
Циклы используются для многократного повторения определенной команды или набора команд. Для выделения тела цикла также используется табуляция.
В Python есть два цикла — while и for.
Цикл while будет повторять команды своего тела до тех пор, пока выполняется условие, записанное для него.
Если возвращаться к аналогии с фрикадельками, которые мы крутим для нашего супчика: этот цикл поможет крутить их до тех пор, пока не будет достаточно.
Структура записи этого цикла:
Например, нам нужно уменьшать значение переменной a в 2 раза нацело до тех пор, пока она не станет меньше или равной переменной b. Для этого в условии цикла прописываем сравнение переменных, а в теле цикла — уменьшение значения переменной a. Пока условие выполняется (то есть принимает значение True), будет выполняться тело цикла, а когда оно перестанет выполняться — свою работу продолжит основной блок кода.
Бесконечный цикл — ситуация, когда цикл while сам по себе никогда не сможет завершить свою работу, то есть значение его условия никогда не перестанет быть равным True.
Но как вообще можно в него попасть?
- Случайно, когда в записи условия работы цикла была допущена ошибка.
В примере — цикл будет работать до тех пор, пока значение переменной b больше 0. Но никакого изменения этой переменной не происходит, она не меняет своего значения, и, соответственно, никогда не станет меньше или равным 0. А значит, цикл никогда не завершит свою работу.
- Специально. Редко, но это имеет смысл. Например, когда условие работы цикла зависит от большого количества параметров. Проще будет прямо в цикле указать, что ему стоит прекратить свою работу.
Для создания бесконечного цикла в условии работы нужно прописать значение, которое ни при каких обстоятельствах не перестанет быть True. Например, это может быть само значение True.
Для остановки цикла используется команда break. Когда цикл натыкается на нее, он моментально прекращает свою работу. Не сработает и последующий блок кода, не будет и следующего шага цикла — программа сразу перескакивает в основной блок кода после цикла.
В примере — мы создали бесконечный цикл, но как только значение a станет меньше или равным b, выполнится условие if и сработает команда break, которая завершит цикл.
Цикл for необходим для выполнения команды или набора команд определенное количество раз или перебора набора данных.
Это тот цикл, который заранее знает, какое количество фрикаделек должно быть в нашем супчике и крутит их до тех пор, пока их не станет конкретное количество.
Структура записи цикла for:
На каждом шаге цикла <переменная> будет принимать новое значение из <диапазона>, после чего будет выполняться <тело цикла>.
По традиции, если перебираемая переменная не несет в себе особой смысловой нагрузки, ее называют i, j или k.
<диапазон> может принимать любое значение, которое можно перебрать. Например:
- перебор строк:
- перебор списка:
- перебор диапазона range, который создает набор целых чисел. Есть несколько способов создания диапазона:
range(a) — диапазон целых чисел от 0 до (a — 1).
Например: range(5) — 0, 1, 2, 3, 4;
range(a, b) — диапазон чисел от a до (b — 1).
Например: range(2, 7) — 2, 3, 4, 5, 6;
range(a, b, step) — диапазон чисел от a до (b — 1) с разницей между соседними числами, равной step.
Например: range(1, 17, 3) — 1, 4, 7, 10, 15.
Вложенные структуры
Имея на вооружении условные конструкции и циклы, разброс наших возможностей сильно возрастает. Но он возрастет еще сильнее, если мы научимся правильно их комбинировать и использовать одно в другом.
Для этого можем воспользоваться вложенными структурами, когда одна конструкция находится внутри другой.
Такой пример уже мелькнул — когда мы говорили о бесконечном цикле и команде break. Мы сделали так, что внутри цикла она выполнится только при истинности условия, для чего прямо внутри цикла while мы использовали условную конструкцию if.
Чтобы программа не сошла с ума, пытаясь понять, где тело цикла, а где тело условия, мы продолжили использовать табуляцию. Весь блок условия находится в цикле, поэтому табуляция цикла никуда не делась. А когда пошло тело вложенного условия — его табуляцию мы начали накладывать прямо поверх предыдущей.
Важно запомнить: если друг в друга вкладывается несколько циклов for, их переменные должны иметь разные имена. |
Вложенные структуры — удобный способ повысить возможности программы. Здесь мы никак не ограничены: мы можем вкладывать циклы в циклы, условия в условия, циклы в условия и так далее. Количество вложений также ничем не ограничено.
Импорт модулей
Для еще большего увеличения мощи нашей программы мы можем использовать модули — наборы инструментов с готовыми решениями части наших задач.
Это легко сравнить с проведением ремонта в квартире. Мы можем что-то сделать простыми инструментами, которые лежат на балконе. Но гораздо эффективнее будет съездить в гараж за специальными инструментами. Так мы не только шкаф — ракету соберём.
Какие есть модули и какие в них есть инструменты — мы будем изучать по мере необходимости. Сейчас главное узнать, как именно это делается. И делать мы это будем на примере модуля math, в котором лежит прекрасная функция sqrt. Она умеет извлекать корни чисел.
Для получения инструментов модуля необходимо произвести его импорт. Сделать это можно несколькими способами:
- Импорт всего модуля:
import math
При такой записи доступ к конкретной функции мы получим, прописав название этого модуля, после него через точку — название необходимой функции.
- Импорт всех функций модуля:
from math import *
При такой записи в нашу программу попадают вообще все функции модуля, для доступа к которым теперь не нужно прописывать название самого модуля.
- Импорт конкретных функций модуля:
from math import sqrt
Такая запись даст нам доступ только к конкретным функциям из всего модуля, которые мы импортируем.
Фактчек
- Табуляция — способ структуризации кода, где отдельные блоки кода выделяются отступами.
- Условная конструкция if-elif-else необходима для выполнения определенных блоков кода при определенных исходах условия.
- Циклы нужны для многократного повторения блока кода. Цикл while выполняет блок кода, пока выполняется переданное ему условие; цикл for перебирает переданные ему значения.
- Импортируя модули, мы можем получить доступ к функциям, которые изначально в программе доступны не были.
Проверь себя
Без запуска кода определите, что будет выведено на экран в результате выполнения программы.
Задание 1.
- 125
- 35
- 90
- 20
Задание 2.
- 275
- 250
- 150
- Ничего
Задание 3.
- 0
- 5
- 10
- 15
Задание 4.
- 10
- 20
- 50
- Ничего
Ответы: 1. — 4; 2. — 3; 3. — 3; 4. — 3.
How do I write a "tab" in Python?
Let’s say I have a file. How do I write «hello» TAB «alex»?
7 Answers 7
This is the code:
The \t inside the string is the escape sequence for the horizontal tabulation.
The Python reference manual includes several string literals that can be used in a string. These special sequences of characters are replaced by the intended meaning of the escape sequence.
Here is a table of some of the more useful escape sequences and a description of the output from them.
Basic Example
If i wanted to print some data points separated by a tab space I could print this string.
Example for Lists
Here is another example where we are printing the items of list and we want to sperate the items by a TAB.
Raw Strings
Note that raw strings (a string which include a prefix «r»), string literals will be ignored. This allows these special sequences of characters to be included in strings without being changed.
Which maybe an undesired output
String Lengths
It should also be noted that string literals are only one character in length.