blob: e9fab58fd0d1da97792dcab00a2b624905756cb5 [file] [log] [blame]
Fred Drakea1cce711998-07-24 22:12:32 +00001\chapter{Lexical analysis\label{lexical}}
Fred Drakef6669171998-05-06 19:52:49 +00002
Fred Drake5c07d9b1998-05-14 19:37:06 +00003A Python program is read by a \emph{parser}. Input to the parser is a
4stream of \emph{tokens}, generated by the \emph{lexical analyzer}. This
Fred Drakef6669171998-05-06 19:52:49 +00005chapter describes how the lexical analyzer breaks a file into tokens.
6\index{lexical analysis}
7\index{parser}
8\index{token}
9
Guido van Rossum60f2f0c1998-06-15 18:00:50 +000010Python uses the 7-bit \ASCII{} character set for program text and string
11literals. 8-bit characters may be used in string literals and comments
12but their interpretation is platform dependent; the proper way to
13insert 8-bit characters in string literals is by using octal or
14hexadecimal escape sequences.
15
16The run-time character set depends on the I/O devices connected to the
Fred Drakec37b65e2001-11-28 07:26:15 +000017program but is generally a superset of \ASCII.
Guido van Rossum60f2f0c1998-06-15 18:00:50 +000018
19\strong{Future compatibility note:} It may be tempting to assume that the
20character set for 8-bit characters is ISO Latin-1 (an \ASCII{}
21superset that covers most western languages that use the Latin
22alphabet), but it is possible that in the future Unicode text editors
23will become common. These generally use the UTF-8 encoding, which is
24also an \ASCII{} superset, but with very different use for the
25characters with ordinals 128-255. While there is no consensus on this
26subject yet, it is unwise to assume either Latin-1 or UTF-8, even
27though the current implementation appears to favor Latin-1. This
28applies both to the source character set and the run-time character
29set.
30
Fred Drakef5eae662001-06-23 05:26:52 +000031
Fred Drake61c77281998-07-28 19:34:22 +000032\section{Line structure\label{line-structure}}
Fred Drakef6669171998-05-06 19:52:49 +000033
Guido van Rossum60f2f0c1998-06-15 18:00:50 +000034A Python program is divided into a number of \emph{logical lines}.
35\index{line structure}
36
Fred Drakef5eae662001-06-23 05:26:52 +000037
Fred Drake61c77281998-07-28 19:34:22 +000038\subsection{Logical lines\label{logical}}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +000039
40The end of
Fred Drakef6669171998-05-06 19:52:49 +000041a logical line is represented by the token NEWLINE. Statements cannot
42cross logical line boundaries except where NEWLINE is allowed by the
Guido van Rossum7c0240f1998-07-24 15:36:43 +000043syntax (e.g., between statements in compound statements).
Guido van Rossum60f2f0c1998-06-15 18:00:50 +000044A logical line is constructed from one or more \emph{physical lines}
45by following the explicit or implicit \emph{line joining} rules.
Fred Drakef6669171998-05-06 19:52:49 +000046\index{logical line}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +000047\index{physical line}
48\index{line joining}
Fred Drakef6669171998-05-06 19:52:49 +000049\index{NEWLINE token}
50
Fred Drakef5eae662001-06-23 05:26:52 +000051
Fred Drake61c77281998-07-28 19:34:22 +000052\subsection{Physical lines\label{physical}}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +000053
54A physical line ends in whatever the current platform's convention is
Fred Drakec37b65e2001-11-28 07:26:15 +000055for terminating lines. On \UNIX, this is the \ASCII{} LF (linefeed)
Guido van Rossum60f2f0c1998-06-15 18:00:50 +000056character. On DOS/Windows, it is the \ASCII{} sequence CR LF (return
57followed by linefeed). On Macintosh, it is the \ASCII{} CR (return)
58character.
59
Fred Drakef5eae662001-06-23 05:26:52 +000060
Fred Drake61c77281998-07-28 19:34:22 +000061\subsection{Comments\label{comments}}
Fred Drakef6669171998-05-06 19:52:49 +000062
Fred Drake5c07d9b1998-05-14 19:37:06 +000063A comment starts with a hash character (\code{\#}) that is not part of
Fred Drakef6669171998-05-06 19:52:49 +000064a string literal, and ends at the end of the physical line. A comment
Guido van Rossum60f2f0c1998-06-15 18:00:50 +000065signifies the end of the logical line unless the implicit line joining
66rules are invoked.
67Comments are ignored by the syntax; they are not tokens.
Fred Drakef6669171998-05-06 19:52:49 +000068\index{comment}
Fred Drakef6669171998-05-06 19:52:49 +000069\index{hash character}
70
Fred Drakef5eae662001-06-23 05:26:52 +000071
Fred Drake61c77281998-07-28 19:34:22 +000072\subsection{Explicit line joining\label{explicit-joining}}
Fred Drakef6669171998-05-06 19:52:49 +000073
74Two or more physical lines may be joined into logical lines using
Fred Drake5c07d9b1998-05-14 19:37:06 +000075backslash characters (\code{\e}), as follows: when a physical line ends
Fred Drakef6669171998-05-06 19:52:49 +000076in a backslash that is not part of a string literal or comment, it is
77joined with the following forming a single logical line, deleting the
78backslash and the following end-of-line character. For example:
79\index{physical line}
80\index{line joining}
81\index{line continuation}
82\index{backslash character}
83%
84\begin{verbatim}
85if 1900 < year < 2100 and 1 <= month <= 12 \
86 and 1 <= day <= 31 and 0 <= hour < 24 \
87 and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date
88 return 1
89\end{verbatim}
90
Guido van Rossum60f2f0c1998-06-15 18:00:50 +000091A line ending in a backslash cannot carry a comment. A backslash does
92not continue a comment. A backslash does not continue a token except
93for string literals (i.e., tokens other than string literals cannot be
94split across physical lines using a backslash). A backslash is
95illegal elsewhere on a line outside a string literal.
Fred Drakef6669171998-05-06 19:52:49 +000096
Fred Drakec411fa61999-02-22 14:32:18 +000097
Fred Drake61c77281998-07-28 19:34:22 +000098\subsection{Implicit line joining\label{implicit-joining}}
Fred Drakef6669171998-05-06 19:52:49 +000099
100Expressions in parentheses, square brackets or curly braces can be
101split over more than one physical line without using backslashes.
102For example:
103
104\begin{verbatim}
105month_names = ['Januari', 'Februari', 'Maart', # These are the
106 'April', 'Mei', 'Juni', # Dutch names
107 'Juli', 'Augustus', 'September', # for the months
108 'Oktober', 'November', 'December'] # of the year
109\end{verbatim}
110
111Implicitly continued lines can carry comments. The indentation of the
112continuation lines is not important. Blank continuation lines are
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000113allowed. There is no NEWLINE token between implicit continuation
114lines. Implicitly continued lines can also occur within triple-quoted
115strings (see below); in that case they cannot carry comments.
Fred Drakef6669171998-05-06 19:52:49 +0000116
Fred Drakef6669171998-05-06 19:52:49 +0000117
Fred Drakec411fa61999-02-22 14:32:18 +0000118\subsection{Blank lines \index{blank line}\label{blank-lines}}
119
120A logical line that contains only spaces, tabs, formfeeds and possibly
121a comment, is ignored (i.e., no NEWLINE token is generated). During
122interactive input of statements, handling of a blank line may differ
123depending on the implementation of the read-eval-print loop. In the
124standard implementation, an entirely blank logical line (i.e.\ one
125containing not even whitespace or a comment) terminates a multi-line
126statement.
127
Fred Drakef6669171998-05-06 19:52:49 +0000128
Fred Drake61c77281998-07-28 19:34:22 +0000129\subsection{Indentation\label{indentation}}
Fred Drakef6669171998-05-06 19:52:49 +0000130
131Leading whitespace (spaces and tabs) at the beginning of a logical
132line is used to compute the indentation level of the line, which in
133turn is used to determine the grouping of statements.
134\index{indentation}
135\index{whitespace}
136\index{leading whitespace}
137\index{space}
138\index{tab}
139\index{grouping}
140\index{statement grouping}
141
142First, tabs are replaced (from left to right) by one to eight spaces
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000143such that the total number of characters up to and including the
144replacement is a multiple of
Fred Drakec37b65e2001-11-28 07:26:15 +0000145eight (this is intended to be the same rule as used by \UNIX). The
Fred Drakef6669171998-05-06 19:52:49 +0000146total number of spaces preceding the first non-blank character then
147determines the line's indentation. Indentation cannot be split over
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000148multiple physical lines using backslashes; the whitespace up to the
149first backslash determines the indentation.
150
151\strong{Cross-platform compatibility note:} because of the nature of
152text editors on non-UNIX platforms, it is unwise to use a mixture of
153spaces and tabs for the indentation in a single source file.
154
155A formfeed character may be present at the start of the line; it will
Fred Drakee15956b2000-04-03 04:51:13 +0000156be ignored for the indentation calculations above. Formfeed
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000157characters occurring elsewhere in the leading whitespace have an
158undefined effect (for instance, they may reset the space count to
159zero).
Fred Drakef6669171998-05-06 19:52:49 +0000160
161The indentation levels of consecutive lines are used to generate
162INDENT and DEDENT tokens, using a stack, as follows.
163\index{INDENT token}
164\index{DEDENT token}
165
166Before the first line of the file is read, a single zero is pushed on
167the stack; this will never be popped off again. The numbers pushed on
168the stack will always be strictly increasing from bottom to top. At
169the beginning of each logical line, the line's indentation level is
170compared to the top of the stack. If it is equal, nothing happens.
171If it is larger, it is pushed on the stack, and one INDENT token is
Fred Drake5c07d9b1998-05-14 19:37:06 +0000172generated. If it is smaller, it \emph{must} be one of the numbers
Fred Drakef6669171998-05-06 19:52:49 +0000173occurring on the stack; all numbers on the stack that are larger are
174popped off, and for each number popped off a DEDENT token is
175generated. At the end of the file, a DEDENT token is generated for
176each number remaining on the stack that is larger than zero.
177
178Here is an example of a correctly (though confusingly) indented piece
179of Python code:
180
181\begin{verbatim}
182def perm(l):
183 # Compute the list of all permutations of l
Fred Drakef6669171998-05-06 19:52:49 +0000184 if len(l) <= 1:
185 return [l]
186 r = []
187 for i in range(len(l)):
188 s = l[:i] + l[i+1:]
189 p = perm(s)
190 for x in p:
191 r.append(l[i:i+1] + x)
192 return r
193\end{verbatim}
194
195The following example shows various indentation errors:
196
197\begin{verbatim}
Fred Drake1d3e6c12001-12-11 17:46:38 +0000198 def perm(l): # error: first line indented
199for i in range(len(l)): # error: not indented
200 s = l[:i] + l[i+1:]
201 p = perm(l[:i] + l[i+1:]) # error: unexpected indent
202 for x in p:
203 r.append(l[i:i+1] + x)
204 return r # error: inconsistent dedent
Fred Drakef6669171998-05-06 19:52:49 +0000205\end{verbatim}
206
207(Actually, the first three errors are detected by the parser; only the
208last error is found by the lexical analyzer --- the indentation of
Fred Drake5c07d9b1998-05-14 19:37:06 +0000209\code{return r} does not match a level popped off the stack.)
Fred Drakef6669171998-05-06 19:52:49 +0000210
Fred Drakef5eae662001-06-23 05:26:52 +0000211
Fred Drake61c77281998-07-28 19:34:22 +0000212\subsection{Whitespace between tokens\label{whitespace}}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000213
214Except at the beginning of a logical line or in string literals, the
215whitespace characters space, tab and formfeed can be used
216interchangeably to separate tokens. Whitespace is needed between two
217tokens only if their concatenation could otherwise be interpreted as a
218different token (e.g., ab is one token, but a b is two tokens).
219
Fred Drakef5eae662001-06-23 05:26:52 +0000220
Fred Drake61c77281998-07-28 19:34:22 +0000221\section{Other tokens\label{other-tokens}}
Fred Drakef6669171998-05-06 19:52:49 +0000222
223Besides NEWLINE, INDENT and DEDENT, the following categories of tokens
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000224exist: \emph{identifiers}, \emph{keywords}, \emph{literals},
225\emph{operators}, and \emph{delimiters}.
226Whitespace characters (other than line terminators, discussed earlier)
227are not tokens, but serve to delimit tokens.
228Where
Fred Drakef6669171998-05-06 19:52:49 +0000229ambiguity exists, a token comprises the longest possible string that
230forms a legal token, when read from left to right.
231
Fred Drakef5eae662001-06-23 05:26:52 +0000232
Fred Drake61c77281998-07-28 19:34:22 +0000233\section{Identifiers and keywords\label{identifiers}}
Fred Drakef6669171998-05-06 19:52:49 +0000234
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000235Identifiers (also referred to as \emph{names}) are described by the following
Fred Drakef6669171998-05-06 19:52:49 +0000236lexical definitions:
237\index{identifier}
238\index{name}
239
Fred Drakecb4638a2001-07-06 22:49:53 +0000240\begin{productionlist}
241 \production{identifier}
242 {(\token{letter}|"_") (\token{letter} | \token{digit} | "_")*}
243 \production{letter}
244 {\token{lowercase} | \token{uppercase}}
245 \production{lowercase}
246 {"a"..."z"}
247 \production{uppercase}
248 {"A"..."Z"}
249 \production{digit}
250 {"0"..."9"}
251\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000252
253Identifiers are unlimited in length. Case is significant.
254
Fred Drakef5eae662001-06-23 05:26:52 +0000255
Fred Drake61c77281998-07-28 19:34:22 +0000256\subsection{Keywords\label{keywords}}
Fred Drakef6669171998-05-06 19:52:49 +0000257
Fred Drake5c07d9b1998-05-14 19:37:06 +0000258The following identifiers are used as reserved words, or
259\emph{keywords} of the language, and cannot be used as ordinary
260identifiers. They must be spelled exactly as written here:%
261\index{keyword}%
Fred Drakef6669171998-05-06 19:52:49 +0000262\index{reserved word}
263
264\begin{verbatim}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000265and del for is raise
266assert elif from lambda return
267break else global not try
Guido van Rossum41c67192001-12-04 20:38:44 +0000268class except if or while
269continue exec import pass yield
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000270def finally in print
Fred Drakef6669171998-05-06 19:52:49 +0000271\end{verbatim}
272
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000273% When adding keywords, use reswords.py for reformatting
274
Fred Drakea23b5732002-06-18 19:17:14 +0000275Note that although the identifier \code{as} can be used as part of the
276syntax of \keyword{import} statements, it is not currently a reserved
277word.
278
279In some future version of Python, the identifiers \code{as} and
280\code{None} will both become keywords.
281
Fred Drakef5eae662001-06-23 05:26:52 +0000282
Fred Drake61c77281998-07-28 19:34:22 +0000283\subsection{Reserved classes of identifiers\label{id-classes}}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000284
285Certain classes of identifiers (besides keywords) have special
286meanings. These are:
287
Fred Drake39fc1bc1999-03-05 18:30:21 +0000288\begin{tableiii}{l|l|l}{code}{Form}{Meaning}{Notes}
289\lineiii{_*}{Not imported by \samp{from \var{module} import *}}{(1)}
290\lineiii{__*__}{System-defined name}{}
291\lineiii{__*}{Class-private name mangling}{}
292\end{tableiii}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000293
294(XXX need section references here.)
Fred Drakef6669171998-05-06 19:52:49 +0000295
Fred Drake39fc1bc1999-03-05 18:30:21 +0000296Note:
297
298\begin{description}
299\item[(1)] The special identifier \samp{_} is used in the interactive
300interpreter to store the result of the last evaluation; it is stored
301in the \module{__builtin__} module. When not in interactive mode,
302\samp{_} has no special meaning and is not defined.
303\end{description}
304
305
Fred Drake61c77281998-07-28 19:34:22 +0000306\section{Literals\label{literals}}
Fred Drakef6669171998-05-06 19:52:49 +0000307
308Literals are notations for constant values of some built-in types.
309\index{literal}
310\index{constant}
311
Fred Drakef5eae662001-06-23 05:26:52 +0000312
Fred Drake61c77281998-07-28 19:34:22 +0000313\subsection{String literals\label{strings}}
Fred Drakef6669171998-05-06 19:52:49 +0000314
315String literals are described by the following lexical definitions:
316\index{string literal}
317
Fred Drakec37b65e2001-11-28 07:26:15 +0000318\index{ASCII@\ASCII}
Fred Drakecb4638a2001-07-06 22:49:53 +0000319\begin{productionlist}
320 \production{stringliteral}
Fred Drakec0cf7262001-08-14 21:43:31 +0000321 {[\token{stringprefix}](\token{shortstring} | \token{longstring})}
322 \production{stringprefix}
323 {"r" | "u" | "ur" | "R" | "U" | "UR" | "Ur" | "uR"}
Fred Drakecb4638a2001-07-06 22:49:53 +0000324 \production{shortstring}
325 {"'" \token{shortstringitem}* "'"
326 | '"' \token{shortstringitem}* '"'}
327 \production{longstring}
Fred Drake53815882002-03-15 23:21:37 +0000328 {"'''" \token{longstringitem}* "'''"}
329 \productioncont{| '"""' \token{longstringitem}* '"""'}
Fred Drakecb4638a2001-07-06 22:49:53 +0000330 \production{shortstringitem}
331 {\token{shortstringchar} | \token{escapeseq}}
332 \production{longstringitem}
333 {\token{longstringchar} | \token{escapeseq}}
334 \production{shortstringchar}
335 {<any ASCII character except "\e" or newline or the quote>}
336 \production{longstringchar}
Fred Drake1d3e6c12001-12-11 17:46:38 +0000337 {<any ASCII character except "\e">}
Fred Drakecb4638a2001-07-06 22:49:53 +0000338 \production{escapeseq}
339 {"\e" <any ASCII character>}
340\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000341
Fred Drakec0cf7262001-08-14 21:43:31 +0000342One syntactic restriction not indicated by these productions is that
343whitespace is not allowed between the \grammartoken{stringprefix} and
344the rest of the string literal.
345
Fred Drakedea764d2000-12-19 04:52:03 +0000346\index{triple-quoted string}
347\index{Unicode Consortium}
348\index{string!Unicode}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000349In plain English: String literals can be enclosed in matching single
350quotes (\code{'}) or double quotes (\code{"}). They can also be
351enclosed in matching groups of three single or double quotes (these
352are generally referred to as \emph{triple-quoted strings}). The
353backslash (\code{\e}) character is used to escape characters that
354otherwise have a special meaning, such as newline, backslash itself,
355or the quote character. String literals may optionally be prefixed
Fred Drakec0cf7262001-08-14 21:43:31 +0000356with a letter `r' or `R'; such strings are called \dfn{raw
357strings}\index{raw string} and use different rules for interpreting
Fred Drakedea764d2000-12-19 04:52:03 +0000358backslash escape sequences. A prefix of 'u' or 'U' makes the string
359a Unicode string. Unicode strings use the Unicode character set as
360defined by the Unicode Consortium and ISO~10646. Some additional
361escape sequences, described below, are available in Unicode strings.
Fred Drakec0cf7262001-08-14 21:43:31 +0000362The two prefix characters may be combined; in this case, `u' must
363appear before `r'.
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000364
365In triple-quoted strings,
Fred Drakef6669171998-05-06 19:52:49 +0000366unescaped newlines and quotes are allowed (and are retained), except
367that three unescaped quotes in a row terminate the string. (A
368``quote'' is the character used to open the string, i.e. either
Fred Drake5c07d9b1998-05-14 19:37:06 +0000369\code{'} or \code{"}.)
Fred Drakef6669171998-05-06 19:52:49 +0000370
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000371Unless an `r' or `R' prefix is present, escape sequences in strings
372are interpreted according to rules similar
Fred Drake90791642001-07-20 15:33:23 +0000373to those used by Standard C. The recognized escape sequences are:
Fred Drakef6669171998-05-06 19:52:49 +0000374\index{physical line}
375\index{escape sequence}
376\index{Standard C}
377\index{C}
378
Fred Drakea1cce711998-07-24 22:12:32 +0000379\begin{tableii}{l|l}{code}{Escape Sequence}{Meaning}
380\lineii{\e\var{newline}} {Ignored}
381\lineii{\e\e} {Backslash (\code{\e})}
382\lineii{\e'} {Single quote (\code{'})}
383\lineii{\e"} {Double quote (\code{"})}
384\lineii{\e a} {\ASCII{} Bell (BEL)}
385\lineii{\e b} {\ASCII{} Backspace (BS)}
386\lineii{\e f} {\ASCII{} Formfeed (FF)}
387\lineii{\e n} {\ASCII{} Linefeed (LF)}
Fred Drakedea764d2000-12-19 04:52:03 +0000388\lineii{\e N\{\var{name}\}}
389 {Character named \var{name} in the Unicode database (Unicode only)}
Fred Drakea1cce711998-07-24 22:12:32 +0000390\lineii{\e r} {\ASCII{} Carriage Return (CR)}
391\lineii{\e t} {\ASCII{} Horizontal Tab (TAB)}
Fred Drakec0cf7262001-08-14 21:43:31 +0000392\lineii{\e u\var{xxxx}} {Character with 16-bit hex value \var{xxxx} (Unicode only)}
393\lineii{\e U\var{xxxxxxxx}}{Character with 32-bit hex value \var{xxxxxxxx} (Unicode only)}
Fred Drakea1cce711998-07-24 22:12:32 +0000394\lineii{\e v} {\ASCII{} Vertical Tab (VT)}
Fred Drakedea764d2000-12-19 04:52:03 +0000395\lineii{\e\var{ooo}} {\ASCII{} character with octal value \var{ooo}}
396\lineii{\e x\var{hh}} {\ASCII{} character with hex value \var{hh}}
Fred Drakea1cce711998-07-24 22:12:32 +0000397\end{tableii}
Fred Drakec37b65e2001-11-28 07:26:15 +0000398\index{ASCII@\ASCII}
Fred Drakef6669171998-05-06 19:52:49 +0000399
Tim Peters75302082001-02-14 04:03:51 +0000400As in Standard C, up to three octal digits are accepted. However,
401exactly two hex digits are taken in hex escapes.
Fred Drakef6669171998-05-06 19:52:49 +0000402
Fred Drakedea764d2000-12-19 04:52:03 +0000403Unlike Standard \index{unrecognized escape sequence}C,
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000404all unrecognized escape sequences are left in the string unchanged,
Fred Drakedea764d2000-12-19 04:52:03 +0000405i.e., \emph{the backslash is left in the string}. (This behavior is
Fred Drakef6669171998-05-06 19:52:49 +0000406useful when debugging: if an escape sequence is mistyped, the
Fred Drakedea764d2000-12-19 04:52:03 +0000407resulting output is more easily recognized as broken.) It is also
408important to note that the escape sequences marked as ``(Unicode
409only)'' in the table above fall into the category of unrecognized
410escapes for non-Unicode string literals.
Fred Drakef6669171998-05-06 19:52:49 +0000411
Fred Drake347a6252001-01-09 21:38:16 +0000412When an `r' or `R' prefix is present, a character following a
413backslash is included in the string without change, and \emph{all
414backslashes are left in the string}. For example, the string literal
415\code{r"\e n"} consists of two characters: a backslash and a lowercase
416`n'. String quotes can be escaped with a backslash, but the backslash
417remains in the string; for example, \code{r"\e""} is a valid string
418literal consisting of two characters: a backslash and a double quote;
Fred Drake0825dc22001-07-20 14:32:28 +0000419\code{r"\e"} is not a valid string literal (even a raw string cannot
Fred Drake347a6252001-01-09 21:38:16 +0000420end in an odd number of backslashes). Specifically, \emph{a raw
421string cannot end in a single backslash} (since the backslash would
422escape the following quote character). Note also that a single
423backslash followed by a newline is interpreted as those two characters
424as part of the string, \emph{not} as a line continuation.
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000425
Fred Drakef5eae662001-06-23 05:26:52 +0000426
Fred Drake61c77281998-07-28 19:34:22 +0000427\subsection{String literal concatenation\label{string-catenation}}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000428
429Multiple adjacent string literals (delimited by whitespace), possibly
430using different quoting conventions, are allowed, and their meaning is
431the same as their concatenation. Thus, \code{"hello" 'world'} is
432equivalent to \code{"helloworld"}. This feature can be used to reduce
433the number of backslashes needed, to split long strings conveniently
434across long lines, or even to add comments to parts of strings, for
435example:
436
437\begin{verbatim}
438re.compile("[A-Za-z_]" # letter or underscore
439 "[A-Za-z0-9_]*" # letter, digit or underscore
440 )
441\end{verbatim}
442
443Note that this feature is defined at the syntactical level, but
444implemented at compile time. The `+' operator must be used to
445concatenate string expressions at run time. Also note that literal
446concatenation can use different quoting styles for each component
447(even mixing raw strings and triple quoted strings).
448
Fred Drake2ed27d32000-11-17 19:05:12 +0000449
Fred Drake61c77281998-07-28 19:34:22 +0000450\subsection{Numeric literals\label{numbers}}
Fred Drakef6669171998-05-06 19:52:49 +0000451
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000452There are four types of numeric literals: plain integers, long
453integers, floating point numbers, and imaginary numbers. There are no
454complex literals (complex numbers can be formed by adding a real
455number and an imaginary number).
Fred Drakef6669171998-05-06 19:52:49 +0000456\index{number}
457\index{numeric literal}
458\index{integer literal}
459\index{plain integer literal}
460\index{long integer literal}
461\index{floating point literal}
462\index{hexadecimal literal}
463\index{octal literal}
464\index{decimal literal}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000465\index{imaginary literal}
Fred Drakeed9e4532002-04-23 20:04:46 +0000466\index{complex!literal}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000467
468Note that numeric literals do not include a sign; a phrase like
469\code{-1} is actually an expression composed of the unary operator
470`\code{-}' and the literal \code{1}.
471
Fred Drakef5eae662001-06-23 05:26:52 +0000472
Fred Drake61c77281998-07-28 19:34:22 +0000473\subsection{Integer and long integer literals\label{integers}}
Fred Drakef6669171998-05-06 19:52:49 +0000474
475Integer and long integer literals are described by the following
476lexical definitions:
477
Fred Drakecb4638a2001-07-06 22:49:53 +0000478\begin{productionlist}
479 \production{longinteger}
480 {\token{integer} ("l" | "L")}
481 \production{integer}
482 {\token{decimalinteger} | \token{octinteger} | \token{hexinteger}}
483 \production{decimalinteger}
484 {\token{nonzerodigit} \token{digit}* | "0"}
485 \production{octinteger}
486 {"0" \token{octdigit}+}
487 \production{hexinteger}
488 {"0" ("x" | "X") \token{hexdigit}+}
489 \production{nonzerodigit}
490 {"1"..."9"}
491 \production{octdigit}
492 {"0"..."7"}
493 \production{hexdigit}
494 {\token{digit} | "a"..."f" | "A"..."F"}
495\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000496
497Although both lower case `l' and upper case `L' are allowed as suffix
498for long integers, it is strongly recommended to always use `L', since
499the letter `l' looks too much like the digit `1'.
500
501Plain integer decimal literals must be at most 2147483647 (i.e., the
502largest positive integer, using 32-bit arithmetic). Plain octal and
503hexadecimal literals may be as large as 4294967295, but values larger
504than 2147483647 are converted to a negative value by subtracting
5054294967296. There is no limit for long integer literals apart from
506what can be stored in available memory.
507
508Some examples of plain and long integer literals:
509
510\begin{verbatim}
5117 2147483647 0177 0x80000000
5123L 79228162514264337593543950336L 0377L 0x100000000L
513\end{verbatim}
514
Fred Drakef5eae662001-06-23 05:26:52 +0000515
Fred Drake61c77281998-07-28 19:34:22 +0000516\subsection{Floating point literals\label{floating}}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000517
Fred Drakef6669171998-05-06 19:52:49 +0000518Floating point literals are described by the following lexical
519definitions:
520
Fred Drakecb4638a2001-07-06 22:49:53 +0000521\begin{productionlist}
522 \production{floatnumber}
523 {\token{pointfloat} | \token{exponentfloat}}
524 \production{pointfloat}
525 {[\token{intpart}] \token{fraction} | \token{intpart} "."}
526 \production{exponentfloat}
Tim Petersd507dab2001-08-30 20:51:59 +0000527 {(\token{intpart} | \token{pointfloat})
Fred Drakecb4638a2001-07-06 22:49:53 +0000528 \token{exponent}}
529 \production{intpart}
Tim Petersd507dab2001-08-30 20:51:59 +0000530 {\token{digit}+}
Fred Drakecb4638a2001-07-06 22:49:53 +0000531 \production{fraction}
532 {"." \token{digit}+}
533 \production{exponent}
534 {("e" | "E") ["+" | "-"] \token{digit}+}
535\end{productionlist}
Fred Drakef6669171998-05-06 19:52:49 +0000536
Tim Petersd507dab2001-08-30 20:51:59 +0000537Note that the integer and exponent parts of floating point numbers
538can look like octal integers, but are interpreted using radix 10. For
539example, \samp{077e010} is legal, and denotes the same number
540as \samp{77e10}.
Fred Drakef6669171998-05-06 19:52:49 +0000541The allowed range of floating point literals is
542implementation-dependent.
Fred Drakef6669171998-05-06 19:52:49 +0000543Some examples of floating point literals:
544
545\begin{verbatim}
Tim Petersd507dab2001-08-30 20:51:59 +00005463.14 10. .001 1e100 3.14e-10 0e0
Fred Drakef6669171998-05-06 19:52:49 +0000547\end{verbatim}
548
549Note that numeric literals do not include a sign; a phrase like
Fred Drake5c07d9b1998-05-14 19:37:06 +0000550\code{-1} is actually an expression composed of the operator
551\code{-} and the literal \code{1}.
Fred Drakef6669171998-05-06 19:52:49 +0000552
Fred Drakef5eae662001-06-23 05:26:52 +0000553
Fred Drake61c77281998-07-28 19:34:22 +0000554\subsection{Imaginary literals\label{imaginary}}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000555
556Imaginary literals are described by the following lexical definitions:
557
Fred Drakecb4638a2001-07-06 22:49:53 +0000558\begin{productionlist}
559 \production{imagnumber}{(\token{floatnumber} | \token{intpart}) ("j" | "J")}
560\end{productionlist}
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000561
Fred Drakee15956b2000-04-03 04:51:13 +0000562An imaginary literal yields a complex number with a real part of
Guido van Rossum60f2f0c1998-06-15 18:00:50 +00005630.0. Complex numbers are represented as a pair of floating point
564numbers and have the same restrictions on their range. To create a
565complex number with a nonzero real part, add a floating point number
Guido van Rossum7c0240f1998-07-24 15:36:43 +0000566to it, e.g., \code{(3+4j)}. Some examples of imaginary literals:
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000567
568\begin{verbatim}
Guido van Rossum7c0240f1998-07-24 15:36:43 +00005693.14j 10.j 10j .001j 1e100j 3.14e-10j
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000570\end{verbatim}
571
572
Fred Drake61c77281998-07-28 19:34:22 +0000573\section{Operators\label{operators}}
Fred Drakef6669171998-05-06 19:52:49 +0000574
575The following tokens are operators:
576\index{operators}
577
578\begin{verbatim}
Fred Drakea7d608d2001-08-08 05:37:21 +0000579+ - * ** / // %
Fred Drakef6669171998-05-06 19:52:49 +0000580<< >> & | ^ ~
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000581< > <= >= == != <>
Fred Drakef6669171998-05-06 19:52:49 +0000582\end{verbatim}
583
Fred Drake5c07d9b1998-05-14 19:37:06 +0000584The comparison operators \code{<>} and \code{!=} are alternate
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000585spellings of the same operator. \code{!=} is the preferred spelling;
586\code{<>} is obsolescent.
Fred Drakef6669171998-05-06 19:52:49 +0000587
Fred Drakef5eae662001-06-23 05:26:52 +0000588
Fred Drake61c77281998-07-28 19:34:22 +0000589\section{Delimiters\label{delimiters}}
Fred Drakef6669171998-05-06 19:52:49 +0000590
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000591The following tokens serve as delimiters in the grammar:
Fred Drakef6669171998-05-06 19:52:49 +0000592\index{delimiters}
593
594\begin{verbatim}
595( ) [ ] { }
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000596, : . ` = ;
Fred Drakea7d608d2001-08-08 05:37:21 +0000597+= -= *= /= //= %=
598&= |= ^= >>= <<= **=
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000599\end{verbatim}
600
601The period can also occur in floating-point and imaginary literals. A
Fred Drakee15956b2000-04-03 04:51:13 +0000602sequence of three periods has a special meaning as an ellipsis in slices.
Thomas Wouters12bba852000-08-24 20:06:04 +0000603The second half of the list, the augmented assignment operators, serve
604lexically as delimiters, but also perform an operation.
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000605
Fred Drakec37b65e2001-11-28 07:26:15 +0000606The following printing \ASCII{} characters have special meaning as part
Guido van Rossum60f2f0c1998-06-15 18:00:50 +0000607of other tokens or are otherwise significant to the lexical analyzer:
608
609\begin{verbatim}
610' " # \
Fred Drakef6669171998-05-06 19:52:49 +0000611\end{verbatim}
612
613The following printing \ASCII{} characters are not used in Python. Their
614occurrence outside string literals and comments is an unconditional
615error:
Fred Drakec37b65e2001-11-28 07:26:15 +0000616\index{ASCII@\ASCII}
Fred Drakef6669171998-05-06 19:52:49 +0000617
618\begin{verbatim}
619@ $ ?
620\end{verbatim}