Python is meant to be an easily readable language. Its formatting is visually uncluttered and often uses English keywords where other languages use punctuation. Unlike many other languages, it does not use
curly brackets to delimit blocks, and semicolons after statements are allowed but rarely used. It has fewer syntactic exceptions and special cases than
C or
Pascal. This feature is sometimes termed the
off-side rule. Some other languages use indentation this way; but in most, indentation has no semantic meaning. The recommended indent size is four spaces.
Statements and control flow Python's
statements include the following: • The
assignment statement, using a single equals sign = • The
if statement, which conditionally executes a block of code, along with
else and elif (a contraction of
else if) • The
for statement, which iterates over an
iterable object, capturing each element to a variable for use by the attached block; the variable is not deleted when the loop finishes • The
while statement, which executes a block of code as long as boolean condition is true • The
try statement, which allows exceptions raised in its attached code block to be caught and handled by except clauses (or new syntax except* in Python 3.11 for exception groups); the try statement also ensures that clean-up code in a finally block is always run regardless of how the block exits • The raise statement, used to raise a specified exception or re-raise a caught exception • The class statement, which executes a block of code and attaches its local namespace to a
class, for use in object-oriented programming • The def statement, which defines a
function or
method • The
with statement, which encloses a code block within a context manager, allowing
resource-acquisition-is-initialization (RAII)-like behavior and replacing a common try/finally idiom Examples of a context include acquiring a
lock before some code is run, and then releasing the lock; or opening and then closing a
file • The
break statement, which exits a loop • The continue statement, which skips the rest of the current iteration and continues with the next • The del statement, which removes a variable—deleting the reference from the name to the value, and producing an error if the variable is referred to before it is redefined • The pass statement, serving as a
NOP (i.e., no operation), which is syntactically needed to create an empty code block • The
assert statement, used in debugging to check for conditions that should apply • The yield statement, which returns a value from a
generator function (and also an operator); used to implement
coroutines • The return statement, used to return a value from a function • The
import and from statements, used to import modules whose functions or variables can be used in the current program. Python 3.15 adds a new functionality to lazily import with a new keyword: "The lazy keyword works with both import and from ... import statements." • The match and case statements, analogous to a
switch statement construct, which compares an expression against one or more cases as a control-flow measure The assignment statement (=) binds a name as a
reference to a separate, dynamically allocated
object. Variables may subsequently be rebound at any time to any object. In Python, a variable name is a generic reference holder without a fixed
data type; however, it always refers to
some object with a type. This is called
dynamic typing—in contrast to
statically-typed languages, where each variable may contain only a value of a certain type. Python does not support
tail call optimization or
first-class continuations; according to Van Rossum, the language never will. Python uses the ** operator for exponentiation. • Python uses the + operator for string concatenation. The language uses the * operator for duplicating a string a specified number of times. • The @ infix operator is intended to be used by libraries such as
NumPy for
matrix multiplication. • The syntax :=, called the "", was introduced in Python 3.8. This operator assigns values to variables as part of a larger expression. • In Python, == compares two objects by value. Python's is operator may be used to compare object identities (i.e., comparison by reference), and comparisons may be chained—for example, . • Python uses and, or, and not as Boolean operators. • Python has a type of expression called a
list comprehension, and a more general expression called a
generator expression. • Python features
sequence unpacking where multiple expressions, each evaluating to something assignable (e.g., a variable or a writable property) are associated just as in forming tuple literal; as a whole, the results are then put on the left-hand side of the equal sign in an assignment statement. This statement expects an
iterable object on the right-hand side of the equal sign to produce the same number of values as the writable expressions on the left-hand side; while iterating, the statement assigns each of the values produced on the right to the corresponding expression on the left. • Python has a "string format" operator % that functions analogously to
printf format strings in the C language—e.g. evaluates to "spam=blah eggs=2". In Python 2.6+ and 3+, this operator was supplemented by the format() method of the str class, e.g., {{code|2=python|1="spam={0} eggs={1}".format("blah", 2)}}. Python 3.6 added "f-strings": {{code|2=python|1=spam = "blah"; eggs = 2; f'spam={spam} eggs={eggs}'}}. • Strings in Python can be
concatenated by "adding" them (using the same operator as for adding integers and floats); e.g., returns "spameggs". If strings contain numbers, they are concatenated as strings rather than as integers, e.g. returns "22". • Python supports
string literals in several ways: • Delimited by single or double quotation marks; single and double quotation marks have equivalent functionality (unlike in
Unix shells,
Perl, and Perl-influenced languages). Both marks use the backslash (\) as an
escape character.
String interpolation became available in Python 3.6 as "formatted string literals". These annotations are not enforced by the language, but may be used by external tools such as
mypy to catch errors. Python includes a module typing including several type names for type annotations. Also, mypy supports a Python compiler called mypyc, which leverages type annotations for optimization.
Arithmetic operations Python includes conventional symbols for arithmetic operators (+, -, *, /), the floor-division operator //, and the
modulo operator %. (With the modulo operator, a remainder can be negative, e.g., 4 % -3 == -2.) Also, Python offers the ** symbol for
exponentiation, e.g. 5**3 == 125 and 9**0.5 == 3.0. Also, it offers the matrix‑multiplication operator @ . These operators work as in traditional mathematics; with the same
precedence rules, the
infix operators + and - can also be
unary, to represent positive and negative numbers respectively. Division between integers produces floating-point results. The behavior of division has changed significantly over time: Due to Python's extensive mathematics library and the third-party library
NumPy, the language is frequently used for scientific scripting in tasks such as numerical data processing and manipulation.
Function syntax Functions are created in Python by using the def keyword. A function is defined similarly to how it is called, by first providing the function name and then the required parameters. Here is an example of a function that prints its inputs: def printer(input1, input2 = "already there"): print(input1) print(input2) printer("hello") • Example output: • hello • already there To assign a default value to a function parameter in case no actual value is provided at run time, variable-definition syntax can be used inside the function header. ==Code examples==