In Python, what is the difference between expressions and statements?
Expressions only contain identifiers, literals and operators, where operators include arithmetic and boolean operators, the function call operator
() the subscription operator
 and similar, and can be reduced to some kind of "value", which can be any Python object. Examples:
3 + 5 map(lambda x: x*x, range(10)) [a.x for a in some_iterable] yield 7
# all the above expressions print 42 if x: do_y() return a = 7
Expression -- from my dictionary:
expression: Mathematics a collection of symbols that jointly express a quantity : the expression for the circumference of a circle is 2πr.
In gross general terms: Expressions produce at least one value.
Examples of expressions:
>>> 23 23 >>> 23l 23L >>> range(4) [0, 1, 2, 3] >>> 2L*bin(2) '0b100b10' >>> def func(a): # Statement, just part of the example... ... return a*a # Statement... ... >>> func(3)*4 36 >>> func(5) is func(a=5) True
Statement from Wikipedia:
In computer programming a statement can be thought of as the smallest standalone element of an imperative programming language. A program is formed by a sequence of one or more statements. A statement will have internal components (e.g., expressions).
In gross general terms: Statements Do Something and are often composed of expressions (or other statements)
The distinction of "Statements do something" and "expressions produce a value" distinction can become blurry however:
ifis usually a statement, such as
if x<0: x=0but you can also have a conditional expression like
x=0 if x<0 else 1that are expressions. In other languages, like C, this form is called an operator like this
def func(a): return a*ais an expression when used but made up of statements when defined.
Noneis a procedure in Python:
def proc(): passSyntactically, you can use
proc()as an expression, but that is probably a bug...
func(x=2);Is that an Expression or Statement? (Answer: Expression used as a Statement with a side-effect.) The form
func(x=2)is illegal in Python (or at least it has a different meaning
func(a=3)sets the named argument