Language
Syntax
Comments
# starts a comment that runs to the end of the line.
# A comment on its own line
x = 1 # A trailing commentA string literal as the first statement of a module, function or class body parses and is discarded. There is no __doc__ at runtime.
Line joining
A statement continues on the next line after a trailing backslash. It also continues freely inside (), [] and {}.
3 ['a', 'b']
Identifiers and assignment
Identifiers start with a letter or underscore and continue with letters, digits and underscores. Non-ASCII characters are allowed.
0 0 0
Tuple unpacking
1 2 1 [2, 3, 4] 5 10 20
Targets can also be attributes, subscripts, parenthesized lists or nested patterns.
[1] 0 3 4 5 6 7
for loops and comprehensions take the same nested targets, as in for i, (k, v) in enumerate(d.items()). A starred target such as *middle must be a plain name.
Walrus operator
:= assigns inside an expression. It helps in conditions and comprehensions.
3
Numbers
Integer literals are decimal by default. The 0x prefix writes hex, 0o octal and 0b binary. _ may separate digits.
Data types covers the range and overflow.
3735928559 511 170 1000000
An underscore must sit between two digits. 1_, 1__2 and 0x_1 are rejected.
Float literals are IEEE-754 doubles.
3.14 1e-05 0.5 1e+16
Complex literals such as 1j do not exist.
Strings
Strings take single, double or triple quotes. Prefixes change what a literal builds.
- An
rprefix makes a raw string. Backslashes stay literal. - A
bprefix builds bytes instead of a string. - An
fprefix makes an f-string.
Adjacent literals concatenate into one.
single double triple quoted raw\n hello world
Escape sequences
| Escape | Meaning |
|---|---|
\n, \t, \r | Line feed, tab, carriage return |
\a, \b, \f, \v | Bell, backspace, form feed, vertical tab |
\\, \', \" | Backslash and quotes |
\0, \NNN | Octal with 1 to 3 digits, \0 is the null character |
\xHH | A character from two hex digits |
\uHHHH, \UHHHHHHHH | A code point from 4 or 8 hex digits |
An unknown escape keeps its backslash. A named escape such as \N{GREEK SMALL LETTER ALPHA} fails at compile time, so write the character or \u03b1.
line break tab A hex é unicode A
f-strings
hello world
answer is 43
0042
3.142
0xff
'world'
{literal braces}The format spec follows these rules.
- The full form is
[[fill]align][sign][#][0][width][,|_][.precision][type]. - The conversions
!r,!sand!acome before the spec. - Type characters are
b c d e E f F g G n o s x X %. ,and_group digits every three for decimal output._withb,o,xorXgroups every four digits.
Operators
Arithmetic
10 4 21 2.3333333333333335 2 1 1024 -5 5
/always yields a float.//and%use floored division. The result of%takes the sign of the divisor.@has no meaning on builtin types. A class can give it one, see Classes.- With a string on the left,
%does printf-style formatting, see Methods.
Comparison and chaining
Comparisons chain, and in, not in, is and is not chain with them. a < b in c means a < b and b in c, with b evaluated once.
Ordering works on numbers, strings and bytes. Lists and tuples compare lexicographically. Mixing types that cannot be ordered raises TypeError.
True True True True
cannot order
Logical
and and or short-circuit. They return the deciding operand, not a coerced bool. not negates.
second fallback default
Bitwise
1 7 6 -6 16 8
Membership and identity
True True True True True
is compares only with None, True, False, ... or NotImplemented. Any other operand fails at compile time, so compare values with ==.
Augmented assignment
The forms are += -= *= /= //= %= **= @= &= |= ^= <<= >>=. A class can define its own in-place behavior, see Classes.
30
Conditional expression
big
Containers
| Literal | Builds |
|---|---|
[1, 2, 3] | A list |
(1, 2, 3) | A tuple |
(1,) | A one-element tuple |
() | An empty tuple |
{"a": 1} | A dict |
{} | An empty dict |
{1, 2, 3} | A set |
{} is an empty dict. The empty set is written set().
Data types covers the semantics and Methods the methods.
(1,) () <class 'dict'> <class 'set'>
Unpacking in literals
* spreads an iterable into a list, set or tuple literal. x = *xs, 3 builds a tuple. ** spreads a mapping into a dict literal.
Both mix freely with regular elements. In a dict, later keys win.
[1, 2, 3, 1, 2]
[1, 2, 3]
{'x': 9, 'y': 2}Indexing and slicing
Indices start at 0. Negative indices count back from the end.
Slices take [start:stop:step]. Any part may be omitted. A negative step walks backwards.
1 5 [2, 3, 4] [1, 2] [4, 5] [1, 3, 5] [5, 4, 3, 2, 1]
Comprehensions
[0, 1, 4, 9, 16]
[0, 2, 4, 6, 8]
[(0, 0), (0, 1), (1, 0), (1, 1)]
[[], [0], [0, 1]]
{0: 0, 1: 1, 2: 4, 3: 9}
[0, 1, 2]Functions covers generator expressions.
Type annotations
Annotations parse on variables, parameters and return positions. They have no runtime effect. There is no __annotations__ and no runtime check.
Treat them as documentation for humans and static analyzers. Generic classes, type aliases and unions are on Data types.
7 ab