What is the difference between an expression and a statement in Python?
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 + 5map(lambda x: x*x, range(10))[a.x for a in some_iterable]yield 7
# all the above expressionsprint 42if x: do_y()returna = 7
Expression -- from the New Oxford American 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:
232323l23Lrange(4)[0, 1, 2, 3] 2L*bin(2)'0b100b10'def func(a): # Statement, just part of the example... return a*a # Statement...func(3)*436 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:
- List Comprehensions are considered "Expressions" but they have looping constructs and therfore also Do Something.
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
- You can write you own Expressions by writing a function.
def func(a): return a*ais an expression when used but made up of statements when defined.
- An expression that returns
Noneis a procedure in Python:
def proc(): passSyntactically, you can use
proc()as an expression, but that is probably a bug...
- Python is a bit more strict than say C is on the differences between an Expression and Statement. In C, any expression is a legal statement. You can have
func(x=2);Is that an Expression or Statement? (Answer: Expression used as a Statement with a side-effect.) The assignment statement of
x=2inside of the function call of
func(x=2)in Python sets the named argument
ato 2 only in the call to
funcand is more limited than the C example.