Syntax#
Python is indentation-sensitive and expression-rich. Indentation defines blocks; statements end at newlines. Continuation inside parentheses, brackets, or braces is implicit; outside them, a trailing backslash joins the line. UTF-8 is the default source encoding.
For the values that syntax produces, see Types. For the operators that combine them, see Operators.
def greet(name):
print(f"hello, {name}")
if __name__ == "__main__":
greet("operator")
Identifiers#
Identifiers are letters, digits, and underscores; they cannot
start with a digit. Conventional case is snake_case for
functions and variables, CamelCase for classes,
UPPER_SNAKE for module-level constants, and
_leading_underscore for “private by convention”.
user_count = 0 # function-scope or module-level
MAX_RETRIES = 5 # module-level constant
class HttpClient: ... # class
_internal = ... # private by convention
__dunder__ = ... # reserved, language-level
Keywords#
Reserved words the operator cannot use as identifiers.
False None True and as assert async await break class continue
def del elif else except finally for from global if import in
is lambda nonlocal not or pass raise return try while with
yield match case
match and case are soft keywords introduced in 3.10; they
are reserved only inside a match statement.
Literals#
Every primitive value has a literal form write directly.
n = 42 # int
big = 1_000_000 # underscores for readability
x = 0xff # hex
o = 0o755 # octal
b = 0b1010_0001 # binary
pi = 3.14159 # float
c = 2 + 3j # complex
s = "hello" # str
r = r"\n is literal" # raw, no escapes
f = f"{n=}, {pi:.2f}" # f-string
m = """multi
line""" # triple-quoted str
bs = b"bytes" # bytes
none = None
Statements#
A statement does something. Assignment, import,
return, raise, def, class, if / for /
while blocks, with blocks. Statements are top-level
constructs the interpreter executes in order; they do not
themselves produce a value.
x = 1 + 2 # assignment statement
import json # import statement
if x > 0: # compound statement
process(x)
for i in range(3): # compound statement
step(i)
return x # return statement
Newlines terminate statements. Semicolons separate them on one line but read as a code smell anywhere outside a one-liner.
Expressions#
An expression evaluates to a value. Arithmetic, function calls, comprehensions, lambdas, conditional expressions (the ternary form), and the walrus operator are all expressions. Anywhere Python wants a value, the operator supplies an expression.
1 + 2 # arithmetic expression
len(xs) > 0 # boolean expression
sum(range(10)) # function-call expression
x if x > 0 else -x # conditional expression (ternary)
[i * i for i in range(5)] # comprehension expression
lambda x: x + 1 # lambda expression
(n := len(xs)) # walrus expression (assigns + evaluates)
Most statements contain expressions: the right-hand side of
an assignment, the condition of an if, the arguments to a
function call. An expression statement is a bare expression
used as a statement; print("hi") and a docstring line both
qualify.
x = 1 + 2 # statement; the 1 + 2 part is an expression
z = x if x > 0 else -x # statement; the if/else part is an expression
print(sum(range(10))) # expression statement
References#
Types for the values literals evaluate to.
Operators for the operators that combine expressions.
Variables for the binding rules that
=invokes.Lexical analysis in the Language Reference.
PEP 8, the style guide.
Comments#
Line comments start with
#and run to the end of the line. Python has no dedicated block-comment syntax; multi-line strings serve as docstrings, which tooling reads.