You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

729 lines
27 KiB

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