blob: 52a09a895c662248113a616b99c075d93eafa8d3 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
2.. _lexical:
3
4****************
5Lexical analysis
6****************
7
8.. index::
9 single: lexical analysis
10 single: parser
11 single: token
12
13A Python program is read by a *parser*. Input to the parser is a stream of
14*tokens*, generated by the *lexical analyzer*. This chapter describes how the
15lexical analyzer breaks a file into tokens.
16
17Python uses the 7-bit ASCII character set for program text.
18
19.. versionadded:: 2.3
20 An encoding declaration can be used to indicate that string literals and
21 comments use an encoding different from ASCII.
22
23For compatibility with older versions, Python only warns if it finds 8-bit
24characters; those warnings should be corrected by either declaring an explicit
25encoding, or using escape sequences if those bytes are binary data, instead of
26characters.
27
28The run-time character set depends on the I/O devices connected to the program
29but is generally a superset of ASCII.
30
31**Future compatibility note:** It may be tempting to assume that the character
32set for 8-bit characters is ISO Latin-1 (an ASCII superset that covers most
33western languages that use the Latin alphabet), but it is possible that in the
34future Unicode text editors will become common. These generally use the UTF-8
35encoding, which is also an ASCII superset, but with very different use for the
36characters with ordinals 128-255. While there is no consensus on this subject
37yet, it is unwise to assume either Latin-1 or UTF-8, even though the current
38implementation appears to favor Latin-1. This applies both to the source
39character set and the run-time character set.
40
41
42.. _line-structure:
43
44Line structure
45==============
46
47.. index:: single: line structure
48
49A Python program is divided into a number of *logical lines*.
50
51
52.. _logical:
53
54Logical lines
55-------------
56
57.. index::
58 single: logical line
59 single: physical line
60 single: line joining
61 single: NEWLINE token
62
63The end of a logical line is represented by the token NEWLINE. Statements
64cannot cross logical line boundaries except where NEWLINE is allowed by the
65syntax (e.g., between statements in compound statements). A logical line is
66constructed from one or more *physical lines* by following the explicit or
67implicit *line joining* rules.
68
69
70.. _physical:
71
72Physical lines
73--------------
74
75A physical line is a sequence of characters terminated by an end-of-line
76sequence. In source files, any of the standard platform line termination
77sequences can be used - the Unix form using ASCII LF (linefeed), the Windows
Georg Brandl9af94982008-09-13 17:41:16 +000078form using the ASCII sequence CR LF (return followed by linefeed), or the old
Georg Brandl8ec7f652007-08-15 14:28:01 +000079Macintosh form using the ASCII CR (return) character. All of these forms can be
80used equally, regardless of platform.
81
82When embedding Python, source code strings should be passed to Python APIs using
83the standard C conventions for newline characters (the ``\n`` character,
84representing ASCII LF, is the line terminator).
85
86
87.. _comments:
88
89Comments
90--------
91
92.. index::
93 single: comment
94 single: hash character
95
96A comment starts with a hash character (``#``) that is not part of a string
97literal, and ends at the end of the physical line. A comment signifies the end
98of the logical line unless the implicit line joining rules are invoked. Comments
99are ignored by the syntax; they are not tokens.
100
101
102.. _encodings:
103
104Encoding declarations
105---------------------
106
R David Murraydd967ef2014-04-16 21:57:38 -0400107.. index:: source character set, encoding declarations (source file)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000108
109If a comment in the first or second line of the Python script matches the
110regular expression ``coding[=:]\s*([-\w.]+)``, this comment is processed as an
111encoding declaration; the first group of this expression names the encoding of
112the source code file. The recommended forms of this expression are ::
113
114 # -*- coding: <encoding-name> -*-
115
116which is recognized also by GNU Emacs, and ::
117
118 # vim:fileencoding=<encoding-name>
119
120which is recognized by Bram Moolenaar's VIM. In addition, if the first bytes of
121the file are the UTF-8 byte-order mark (``'\xef\xbb\xbf'``), the declared file
122encoding is UTF-8 (this is supported, among others, by Microsoft's
123:program:`notepad`).
124
125If an encoding is declared, the encoding name must be recognized by Python. The
126encoding is used for all lexical analysis, in particular to find the end of a
127string, and to interpret the contents of Unicode literals. String literals are
128converted to Unicode for syntactical analysis, then converted back to their
129original encoding before interpretation starts. The encoding declaration must
130appear on a line of its own.
131
Georg Brandlb19be572007-12-29 10:57:00 +0000132.. XXX there should be a list of supported encodings.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000133
134
135.. _explicit-joining:
136
137Explicit line joining
138---------------------
139
140.. index::
141 single: physical line
142 single: line joining
143 single: line continuation
144 single: backslash character
145
146Two or more physical lines may be joined into logical lines using backslash
147characters (``\``), as follows: when a physical line ends in a backslash that is
148not part of a string literal or comment, it is joined with the following forming
149a single logical line, deleting the backslash and the following end-of-line
Georg Brandlb19be572007-12-29 10:57:00 +0000150character. For example::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000151
152 if 1900 < year < 2100 and 1 <= month <= 12 \
153 and 1 <= day <= 31 and 0 <= hour < 24 \
154 and 0 <= minute < 60 and 0 <= second < 60: # Looks like a valid date
155 return 1
156
157A line ending in a backslash cannot carry a comment. A backslash does not
158continue a comment. A backslash does not continue a token except for string
159literals (i.e., tokens other than string literals cannot be split across
160physical lines using a backslash). A backslash is illegal elsewhere on a line
161outside a string literal.
162
163
164.. _implicit-joining:
165
166Implicit line joining
167---------------------
168
169Expressions in parentheses, square brackets or curly braces can be split over
170more than one physical line without using backslashes. For example::
171
172 month_names = ['Januari', 'Februari', 'Maart', # These are the
173 'April', 'Mei', 'Juni', # Dutch names
174 'Juli', 'Augustus', 'September', # for the months
175 'Oktober', 'November', 'December'] # of the year
176
177Implicitly continued lines can carry comments. The indentation of the
178continuation lines is not important. Blank continuation lines are allowed.
179There is no NEWLINE token between implicit continuation lines. Implicitly
180continued lines can also occur within triple-quoted strings (see below); in that
181case they cannot carry comments.
182
183
184.. _blank-lines:
185
186Blank lines
187-----------
188
189.. index:: single: blank line
190
191A logical line that contains only spaces, tabs, formfeeds and possibly a
192comment, is ignored (i.e., no NEWLINE token is generated). During interactive
193input of statements, handling of a blank line may differ depending on the
194implementation of the read-eval-print loop. In the standard implementation, an
195entirely blank logical line (i.e. one containing not even whitespace or a
196comment) terminates a multi-line statement.
197
198
199.. _indentation:
200
201Indentation
202-----------
203
204.. index::
205 single: indentation
206 single: whitespace
207 single: leading whitespace
208 single: space
209 single: tab
210 single: grouping
211 single: statement grouping
212
213Leading whitespace (spaces and tabs) at the beginning of a logical line is used
214to compute the indentation level of the line, which in turn is used to determine
215the grouping of statements.
216
217First, tabs are replaced (from left to right) by one to eight spaces such that
218the total number of characters up to and including the replacement is a multiple
219of eight (this is intended to be the same rule as used by Unix). The total
220number of spaces preceding the first non-blank character then determines the
221line's indentation. Indentation cannot be split over multiple physical lines
222using backslashes; the whitespace up to the first backslash determines the
223indentation.
224
225**Cross-platform compatibility note:** because of the nature of text editors on
226non-UNIX platforms, it is unwise to use a mixture of spaces and tabs for the
227indentation in a single source file. It should also be noted that different
228platforms may explicitly limit the maximum indentation level.
229
230A formfeed character may be present at the start of the line; it will be ignored
231for the indentation calculations above. Formfeed characters occurring elsewhere
232in the leading whitespace have an undefined effect (for instance, they may reset
233the space count to zero).
234
235.. index::
236 single: INDENT token
237 single: DEDENT token
238
239The indentation levels of consecutive lines are used to generate INDENT and
240DEDENT tokens, using a stack, as follows.
241
242Before the first line of the file is read, a single zero is pushed on the stack;
243this will never be popped off again. The numbers pushed on the stack will
244always be strictly increasing from bottom to top. At the beginning of each
245logical line, the line's indentation level is compared to the top of the stack.
246If it is equal, nothing happens. If it is larger, it is pushed on the stack, and
247one INDENT token is generated. If it is smaller, it *must* be one of the
248numbers occurring on the stack; all numbers on the stack that are larger are
249popped off, and for each number popped off a DEDENT token is generated. At the
250end of the file, a DEDENT token is generated for each number remaining on the
251stack that is larger than zero.
252
253Here is an example of a correctly (though confusingly) indented piece of Python
254code::
255
256 def perm(l):
257 # Compute the list of all permutations of l
258 if len(l) <= 1:
259 return [l]
260 r = []
261 for i in range(len(l)):
262 s = l[:i] + l[i+1:]
263 p = perm(s)
264 for x in p:
265 r.append(l[i:i+1] + x)
266 return r
267
268The following example shows various indentation errors::
269
270 def perm(l): # error: first line indented
271 for i in range(len(l)): # error: not indented
272 s = l[:i] + l[i+1:]
273 p = perm(l[:i] + l[i+1:]) # error: unexpected indent
274 for x in p:
275 r.append(l[i:i+1] + x)
276 return r # error: inconsistent dedent
277
278(Actually, the first three errors are detected by the parser; only the last
279error is found by the lexical analyzer --- the indentation of ``return r`` does
280not match a level popped off the stack.)
281
282
283.. _whitespace:
284
285Whitespace between tokens
286-------------------------
287
288Except at the beginning of a logical line or in string literals, the whitespace
289characters space, tab and formfeed can be used interchangeably to separate
290tokens. Whitespace is needed between two tokens only if their concatenation
291could otherwise be interpreted as a different token (e.g., ab is one token, but
292a b is two tokens).
293
294
295.. _other-tokens:
296
297Other tokens
298============
299
300Besides NEWLINE, INDENT and DEDENT, the following categories of tokens exist:
301*identifiers*, *keywords*, *literals*, *operators*, and *delimiters*. Whitespace
302characters (other than line terminators, discussed earlier) are not tokens, but
303serve to delimit tokens. Where ambiguity exists, a token comprises the longest
304possible string that forms a legal token, when read from left to right.
305
306
307.. _identifiers:
308
309Identifiers and keywords
310========================
311
312.. index::
313 single: identifier
314 single: name
315
316Identifiers (also referred to as *names*) are described by the following lexical
317definitions:
318
319.. productionlist::
320 identifier: (`letter`|"_") (`letter` | `digit` | "_")*
321 letter: `lowercase` | `uppercase`
322 lowercase: "a"..."z"
323 uppercase: "A"..."Z"
324 digit: "0"..."9"
325
326Identifiers are unlimited in length. Case is significant.
327
328
329.. _keywords:
330
331Keywords
332--------
333
334.. index::
335 single: keyword
336 single: reserved word
337
338The following identifiers are used as reserved words, or *keywords* of the
339language, and cannot be used as ordinary identifiers. They must be spelled
Georg Brandl2ca9be42009-05-04 20:42:08 +0000340exactly as written here:
341
342.. sourcecode:: text
Georg Brandl8ec7f652007-08-15 14:28:01 +0000343
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000344 and del from not while
345 as elif global or with
346 assert else if pass yield
347 break except import print
348 class exec in raise
349 continue finally is return
350 def for lambda try
Georg Brandl8ec7f652007-08-15 14:28:01 +0000351
352.. versionchanged:: 2.4
353 :const:`None` became a constant and is now recognized by the compiler as a name
354 for the built-in object :const:`None`. Although it is not a keyword, you cannot
355 assign a different object to it.
356
357.. versionchanged:: 2.5
Terry Jan Reedy96a0a462012-01-21 00:24:25 -0500358 Using :keyword:`as` and :keyword:`with` as identifiers triggers a warning. To
359 use them as keywords, enable the ``with_statement`` future feature .
Terry Jan Reedy0bb12512012-01-21 00:32:23 -0500360
Terry Jan Reedy96a0a462012-01-21 00:24:25 -0500361.. versionchanged:: 2.6
362 :keyword:`as` and :keyword:`with` are full keywords.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000363
Terry Jan Reedy0bb12512012-01-21 00:32:23 -0500364
Georg Brandl8ec7f652007-08-15 14:28:01 +0000365.. _id-classes:
366
367Reserved classes of identifiers
368-------------------------------
369
370Certain classes of identifiers (besides keywords) have special meanings. These
371classes are identified by the patterns of leading and trailing underscore
372characters:
373
374``_*``
375 Not imported by ``from module import *``. The special identifier ``_`` is used
376 in the interactive interpreter to store the result of the last evaluation; it is
377 stored in the :mod:`__builtin__` module. When not in interactive mode, ``_``
378 has no special meaning and is not defined. See section :ref:`import`.
379
380 .. note::
381
382 The name ``_`` is often used in conjunction with internationalization;
383 refer to the documentation for the :mod:`gettext` module for more
384 information on this convention.
385
386``__*__``
Georg Brandl7d4bfb32010-08-02 21:44:25 +0000387 System-defined names. These names are defined by the interpreter and its
388 implementation (including the standard library). Current system names are
389 discussed in the :ref:`specialnames` section and elsewhere. More will likely
390 be defined in future versions of Python. *Any* use of ``__*__`` names, in
391 any context, that does not follow explicitly documented use, is subject to
392 breakage without warning.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000393
394``__*``
395 Class-private names. Names in this category, when used within the context of a
396 class definition, are re-written to use a mangled form to help avoid name
397 clashes between "private" attributes of base and derived classes. See section
398 :ref:`atom-identifiers`.
399
400
401.. _literals:
402
403Literals
404========
405
406.. index::
407 single: literal
408 single: constant
409
410Literals are notations for constant values of some built-in types.
411
412
413.. _strings:
414
415String literals
416---------------
417
418.. index:: single: string literal
419
420String literals are described by the following lexical definitions:
421
422.. index:: single: ASCII@ASCII
423
424.. productionlist::
425 stringliteral: [`stringprefix`](`shortstring` | `longstring`)
426 stringprefix: "r" | "u" | "ur" | "R" | "U" | "UR" | "Ur" | "uR"
Georg Brandl7db964d2010-09-25 13:46:23 +0000427 : | "b" | "B" | "br" | "Br" | "bR" | "BR"
Georg Brandl8ec7f652007-08-15 14:28:01 +0000428 shortstring: "'" `shortstringitem`* "'" | '"' `shortstringitem`* '"'
Georg Brandl03894c52008-08-06 17:20:41 +0000429 longstring: "'''" `longstringitem`* "'''"
Georg Brandl8ec7f652007-08-15 14:28:01 +0000430 : | '"""' `longstringitem`* '"""'
431 shortstringitem: `shortstringchar` | `escapeseq`
432 longstringitem: `longstringchar` | `escapeseq`
433 shortstringchar: <any source character except "\" or newline or the quote>
434 longstringchar: <any source character except "\">
435 escapeseq: "\" <any ASCII character>
436
437One syntactic restriction not indicated by these productions is that whitespace
438is not allowed between the :token:`stringprefix` and the rest of the string
439literal. The source character set is defined by the encoding declaration; it is
440ASCII if no encoding declaration is given in the source file; see section
441:ref:`encodings`.
442
443.. index::
444 single: triple-quoted string
445 single: Unicode Consortium
446 single: string; Unicode
447 single: raw string
448
449In plain English: String literals can be enclosed in matching single quotes
450(``'``) or double quotes (``"``). They can also be enclosed in matching groups
451of three single or double quotes (these are generally referred to as
452*triple-quoted strings*). The backslash (``\``) character is used to escape
453characters that otherwise have a special meaning, such as newline, backslash
454itself, or the quote character. String literals may optionally be prefixed with
455a letter ``'r'`` or ``'R'``; such strings are called :dfn:`raw strings` and use
456different rules for interpreting backslash escape sequences. A prefix of
457``'u'`` or ``'U'`` makes the string a Unicode string. Unicode strings use the
458Unicode character set as defined by the Unicode Consortium and ISO 10646. Some
459additional escape sequences, described below, are available in Unicode strings.
Georg Brandl7db964d2010-09-25 13:46:23 +0000460A prefix of ``'b'`` or ``'B'`` is ignored in Python 2; it indicates that the
461literal should become a bytes literal in Python 3 (e.g. when code is
462automatically converted with 2to3). A ``'u'`` or ``'b'`` prefix may be followed
463by an ``'r'`` prefix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000464
465In triple-quoted strings, unescaped newlines and quotes are allowed (and are
466retained), except that three unescaped quotes in a row terminate the string. (A
467"quote" is the character used to open the string, i.e. either ``'`` or ``"``.)
468
469.. index::
470 single: physical line
471 single: escape sequence
472 single: Standard C
473 single: C
474
475Unless an ``'r'`` or ``'R'`` prefix is present, escape sequences in strings are
476interpreted according to rules similar to those used by Standard C. The
477recognized escape sequences are:
478
479+-----------------+---------------------------------+-------+
480| Escape Sequence | Meaning | Notes |
481+=================+=================================+=======+
482| ``\newline`` | Ignored | |
483+-----------------+---------------------------------+-------+
484| ``\\`` | Backslash (``\``) | |
485+-----------------+---------------------------------+-------+
486| ``\'`` | Single quote (``'``) | |
487+-----------------+---------------------------------+-------+
488| ``\"`` | Double quote (``"``) | |
489+-----------------+---------------------------------+-------+
490| ``\a`` | ASCII Bell (BEL) | |
491+-----------------+---------------------------------+-------+
492| ``\b`` | ASCII Backspace (BS) | |
493+-----------------+---------------------------------+-------+
494| ``\f`` | ASCII Formfeed (FF) | |
495+-----------------+---------------------------------+-------+
496| ``\n`` | ASCII Linefeed (LF) | |
497+-----------------+---------------------------------+-------+
498| ``\N{name}`` | Character named *name* in the | |
499| | Unicode database (Unicode only) | |
500+-----------------+---------------------------------+-------+
501| ``\r`` | ASCII Carriage Return (CR) | |
502+-----------------+---------------------------------+-------+
503| ``\t`` | ASCII Horizontal Tab (TAB) | |
504+-----------------+---------------------------------+-------+
505| ``\uxxxx`` | Character with 16-bit hex value | \(1) |
506| | *xxxx* (Unicode only) | |
507+-----------------+---------------------------------+-------+
508| ``\Uxxxxxxxx`` | Character with 32-bit hex value | \(2) |
509| | *xxxxxxxx* (Unicode only) | |
510+-----------------+---------------------------------+-------+
511| ``\v`` | ASCII Vertical Tab (VT) | |
512+-----------------+---------------------------------+-------+
513| ``\ooo`` | Character with octal value | (3,5) |
514| | *ooo* | |
515+-----------------+---------------------------------+-------+
516| ``\xhh`` | Character with hex value *hh* | (4,5) |
517+-----------------+---------------------------------+-------+
518
519.. index:: single: ASCII@ASCII
520
521Notes:
522
523(1)
524 Individual code units which form parts of a surrogate pair can be encoded using
525 this escape sequence.
526
527(2)
528 Any Unicode character can be encoded this way, but characters outside the Basic
529 Multilingual Plane (BMP) will be encoded using a surrogate pair if Python is
Terry Jan Reedy241f6532013-07-27 15:54:05 -0400530 compiled to use 16-bit code units (the default).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000531
532(3)
533 As in Standard C, up to three octal digits are accepted.
534
535(4)
Georg Brandl953e1ee2008-01-22 07:53:31 +0000536 Unlike in Standard C, exactly two hex digits are required.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000537
538(5)
539 In a string literal, hexadecimal and octal escapes denote the byte with the
540 given value; it is not necessary that the byte encodes a character in the source
541 character set. In a Unicode literal, these escapes denote a Unicode character
542 with the given value.
543
544.. index:: single: unrecognized escape sequence
545
546Unlike Standard C, all unrecognized escape sequences are left in the string
547unchanged, i.e., *the backslash is left in the string*. (This behavior is
548useful when debugging: if an escape sequence is mistyped, the resulting output
549is more easily recognized as broken.) It is also important to note that the
550escape sequences marked as "(Unicode only)" in the table above fall into the
551category of unrecognized escapes for non-Unicode string literals.
552
553When an ``'r'`` or ``'R'`` prefix is present, a character following a backslash
554is included in the string without change, and *all backslashes are left in the
555string*. For example, the string literal ``r"\n"`` consists of two characters:
556a backslash and a lowercase ``'n'``. String quotes can be escaped with a
557backslash, but the backslash remains in the string; for example, ``r"\""`` is a
558valid string literal consisting of two characters: a backslash and a double
559quote; ``r"\"`` is not a valid string literal (even a raw string cannot end in
560an odd number of backslashes). Specifically, *a raw string cannot end in a
561single backslash* (since the backslash would escape the following quote
562character). Note also that a single backslash followed by a newline is
563interpreted as those two characters as part of the string, *not* as a line
564continuation.
565
566When an ``'r'`` or ``'R'`` prefix is used in conjunction with a ``'u'`` or
567``'U'`` prefix, then the ``\uXXXX`` and ``\UXXXXXXXX`` escape sequences are
568processed while *all other backslashes are left in the string*. For example,
569the string literal ``ur"\u0062\n"`` consists of three Unicode characters: 'LATIN
570SMALL LETTER B', 'REVERSE SOLIDUS', and 'LATIN SMALL LETTER N'. Backslashes can
571be escaped with a preceding backslash; however, both remain in the string. As a
572result, ``\uXXXX`` escape sequences are only recognized when there are an odd
573number of backslashes.
574
575
576.. _string-catenation:
577
578String literal concatenation
579----------------------------
580
581Multiple adjacent string literals (delimited by whitespace), possibly using
582different quoting conventions, are allowed, and their meaning is the same as
583their concatenation. Thus, ``"hello" 'world'`` is equivalent to
584``"helloworld"``. This feature can be used to reduce the number of backslashes
585needed, to split long strings conveniently across long lines, or even to add
586comments to parts of strings, for example::
587
588 re.compile("[A-Za-z_]" # letter or underscore
589 "[A-Za-z0-9_]*" # letter, digit or underscore
590 )
591
592Note that this feature is defined at the syntactical level, but implemented at
593compile time. The '+' operator must be used to concatenate string expressions
594at run time. Also note that literal concatenation can use different quoting
595styles for each component (even mixing raw strings and triple quoted strings).
596
597
598.. _numbers:
599
600Numeric literals
601----------------
602
603.. index::
604 single: number
605 single: numeric literal
606 single: integer literal
607 single: plain integer literal
608 single: long integer literal
609 single: floating point literal
610 single: hexadecimal literal
Benjamin Petersond79af0f2008-10-30 22:44:18 +0000611 single: binary literal
Georg Brandl8ec7f652007-08-15 14:28:01 +0000612 single: octal literal
613 single: decimal literal
614 single: imaginary literal
615 single: complex; literal
616
617There are four types of numeric literals: plain integers, long integers,
618floating point numbers, and imaginary numbers. There are no complex literals
619(complex numbers can be formed by adding a real number and an imaginary number).
620
621Note that numeric literals do not include a sign; a phrase like ``-1`` is
622actually an expression composed of the unary operator '``-``' and the literal
623``1``.
624
625
626.. _integers:
627
628Integer and long integer literals
629---------------------------------
630
631Integer and long integer literals are described by the following lexical
632definitions:
633
634.. productionlist::
635 longinteger: `integer` ("l" | "L")
Benjamin Petersonb5f82082008-10-30 22:39:25 +0000636 integer: `decimalinteger` | `octinteger` | `hexinteger` | `bininteger`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000637 decimalinteger: `nonzerodigit` `digit`* | "0"
Benjamin Petersond79af0f2008-10-30 22:44:18 +0000638 octinteger: "0" ("o" | "O") `octdigit`+ | "0" `octdigit`+
Georg Brandl8ec7f652007-08-15 14:28:01 +0000639 hexinteger: "0" ("x" | "X") `hexdigit`+
Benjamin Petersonb5f82082008-10-30 22:39:25 +0000640 bininteger: "0" ("b" | "B") `bindigit`+
Georg Brandl8ec7f652007-08-15 14:28:01 +0000641 nonzerodigit: "1"..."9"
642 octdigit: "0"..."7"
Benjamin Petersond79af0f2008-10-30 22:44:18 +0000643 bindigit: "0" | "1"
Georg Brandl8ec7f652007-08-15 14:28:01 +0000644 hexdigit: `digit` | "a"..."f" | "A"..."F"
645
646Although both lower case ``'l'`` and upper case ``'L'`` are allowed as suffix
647for long integers, it is strongly recommended to always use ``'L'``, since the
648letter ``'l'`` looks too much like the digit ``'1'``.
649
650Plain integer literals that are above the largest representable plain integer
651(e.g., 2147483647 when using 32-bit arithmetic) are accepted as if they were
652long integers instead. [#]_ There is no limit for long integer literals apart
653from what can be stored in available memory.
654
655Some examples of plain integer literals (first row) and long integer literals
656(second and third rows)::
657
658 7 2147483647 0177
659 3L 79228162514264337593543950336L 0377L 0x100000000L
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000660 79228162514264337593543950336 0xdeadbeef
Georg Brandl8ec7f652007-08-15 14:28:01 +0000661
662
663.. _floating:
664
665Floating point literals
666-----------------------
667
668Floating point literals are described by the following lexical definitions:
669
670.. productionlist::
671 floatnumber: `pointfloat` | `exponentfloat`
672 pointfloat: [`intpart`] `fraction` | `intpart` "."
673 exponentfloat: (`intpart` | `pointfloat`) `exponent`
674 intpart: `digit`+
675 fraction: "." `digit`+
676 exponent: ("e" | "E") ["+" | "-"] `digit`+
677
678Note that the integer and exponent parts of floating point numbers can look like
679octal integers, but are interpreted using radix 10. For example, ``077e010`` is
680legal, and denotes the same number as ``77e10``. The allowed range of floating
681point literals is implementation-dependent. Some examples of floating point
682literals::
683
684 3.14 10. .001 1e100 3.14e-10 0e0
685
686Note that numeric literals do not include a sign; a phrase like ``-1`` is
687actually an expression composed of the unary operator ``-`` and the literal
688``1``.
689
690
691.. _imaginary:
692
693Imaginary literals
694------------------
695
696Imaginary literals are described by the following lexical definitions:
697
698.. productionlist::
699 imagnumber: (`floatnumber` | `intpart`) ("j" | "J")
700
701An imaginary literal yields a complex number with a real part of 0.0. Complex
702numbers are represented as a pair of floating point numbers and have the same
703restrictions on their range. To create a complex number with a nonzero real
704part, add a floating point number to it, e.g., ``(3+4j)``. Some examples of
705imaginary literals::
706
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000707 3.14j 10.j 10j .001j 1e100j 3.14e-10j
Georg Brandl8ec7f652007-08-15 14:28:01 +0000708
709
710.. _operators:
711
712Operators
713=========
714
715.. index:: single: operators
716
717The following tokens are operators::
718
719 + - * ** / // %
720 << >> & | ^ ~
721 < > <= >= == != <>
722
723The comparison operators ``<>`` and ``!=`` are alternate spellings of the same
724operator. ``!=`` is the preferred spelling; ``<>`` is obsolescent.
725
726
727.. _delimiters:
728
729Delimiters
730==========
731
732.. index:: single: delimiters
733
734The following tokens serve as delimiters in the grammar::
735
736 ( ) [ ] { } @
737 , : . ` = ;
738 += -= *= /= //= %=
739 &= |= ^= >>= <<= **=
740
741The period can also occur in floating-point and imaginary literals. A sequence
742of three periods has a special meaning as an ellipsis in slices. The second half
743of the list, the augmented assignment operators, serve lexically as delimiters,
744but also perform an operation.
745
746The following printing ASCII characters have special meaning as part of other
747tokens or are otherwise significant to the lexical analyzer::
748
749 ' " # \
750
751.. index:: single: ASCII@ASCII
752
753The following printing ASCII characters are not used in Python. Their
754occurrence outside string literals and comments is an unconditional error::
755
756 $ ?
757
758.. rubric:: Footnotes
759
760.. [#] In versions of Python prior to 2.4, octal and hexadecimal literals in the range
761 just above the largest representable plain integer but below the largest
762 unsigned 32-bit number (on a machine using 32-bit arithmetic), 4294967296, were
763 taken as the negative plain integer obtained by subtracting 4294967296 from
764 their unsigned value.
765