A statement is an instruction that the Python interpreter executes. Statements do not return a value; they are simply executed.
A simple statement fits on one line. Simple statements may occur on a single line separated by semicolons.
An assignment statement is used to bind variable names to values and to modify attributes of mutable objects.
= operator is used:
var = val
Python also supports multiple assignment:
var1, var2 = val1, val2 # equivalent to: # var1 = val1 # var2 = val2
An assignment is executed in the following way:
- evaluate the right of the equals sign
- bind the name(s) on the left to the resulting value
If a name is already bound to a value, the old value is overwritten by the new value. Example:
>>> a = 2; a = 3 >>> a # a takes on the last value it was bound to 3
Assignment statements in the form
x = x op y can be shortened to
x op= y, where
op is an arithmetic operator. Example:
>>> a = 2 >>> a += 1 # equivalent to a = a + 1 >>> a 3
The assert statement is used as a debugging assertion. The syntax is
assert expr, where
expr is a boolean expression. If
expr evaluates to
False (i.e., the check fails), an
AssertionError is thrown. Otherwise, nothing happens.
Adding another argument allows you to specify a debugging message when the check fails:
assert expr, msg.
>>> x = -5 >>> assert x == -5 >>> assert x % 2 == 0, "x is not even" Traceback (most recent call last): ... AssertionError: x is not even >>> assert x > 0 Traceback (most recent call last): ... AssertionError
pass is a null operation—when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed.
# a class with no methods or attributes class A: pass # omitting this would result in an IndentationError # complex conditional if condA and (condB or condC): pass # do nothing else: # ...
return expr leaves the current function call with
expr as a return value. If
expr is omitted or there is no
return statement in the function, the return value is
return can occur only in a function definition.
>>> def fn(): ... return 3 ... >>> fn() 3
- Main article: Generator
- Main article: Exception
- Main article: Iteration#break statement
- Main article: Iteration#continue statement
An import statement loads a module into the program. A module is a file containing Python definitions and statements.
>>> from operator import add >>> add(2, 3) 5 >>> from functools import reduce >>> reduce(add, [1, 2, 3]) 6
global var tells Python to modify the binding of
var in the global frame if it exists instead of creating a new binding in the current frame. Example:
>>> a = 0 >>> def fn(): ... global a ... a += 1 ... >>> a 0 >>> fn() >>> a 1
nonlocal var behaves the same, except for
var in a parent (but non-global) frame. Example:
>>> def fn(x): ... def inner(): ... nonlocal x ... x += 1 ... inner() ... return x ... >>> fn(1) 2
Compound statements contain groups of other statements. Compound statements generally provide control flow (controlling the execution of the enclosed statements) and span multiple lines.
A compound statement consists of one or more clauses, which consists of a header and a suite. The header ends with a colon (:) and controls the suite that follows; the suite is a sequence of statements.
Conditional statements are used to perform different actions depending on some boolean condition. The syntax is:
if condition1: ... elif condition2: ... else: ...
condition2 are boolean expressions. If
condition1 evaluates to
True, its suite is executed and the rest of the compound statement is skipped. Otherwise, Python checks
condition2. If that evaluates to
True, the second suite is executed and the rest of the compound statement is skipped. Otherwise, the
else suite is executed.
else clauses are optional, and there may be more than one
import datetime hour = datetime.datetime.now().hour # returns the current hour (24-hour clock) if hour < 10: print("Good morning") elif hour < 12: print("Soon time for lunch") elif hour < 18: print("Good day") elif x < 22: print("Good evening") else: print("Good night")
A conditional statement can be a one-liner through Python's version of the ternary operator. The syntax is:
expression1 if condition else expression2. If
condition evaluates to
expression1 is returned, otherwise
expression2 is returned. Examples:
>>> x = -3 >>> "x is negative" if x < 0 else "x is nonnegative" 'x is negative' >>> x = 0 >>> "x is negative" if x < 0 else ("x is zero" if x == 0 else "x is positive") # chained 'x is zero'
- Main article: Iteration#While loop
- Main article: Iteration#For loop
- Main article: Exception
The syntax of a function definition is:
def fn(param1, param2): ...
param2 are formal parameters. They are the names that the passed in arguments will be bound to.
If parameters are of the form
param = expression, the function is said to have default parameter values. When the corresponding argument is omitted in a function call, the parameter's default value is used. Example:
>>> def fn(a, b=2): ... return a + b ... >>> fn(1, 1) 2 >>> fn(1) # omitted b 3
A function definition is executed in the following way:
- create a function object with signature
- set the body of that function to be everything indented after the first line
- bind the function name to the function object in the current frame
- Main article: Object-oriented programming