/Doc/reference/lexical_analysis.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 764 lines · 569 code · 195 blank · 0 comment · 0 complexity · 2d2b082c3b7944d650aa47971f87d75c MD5 · raw file

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