In Python, what is the difference between expressions and statements?
-
Due to python's definition that expressions are a subset of statements, the question can be revised as: which statements are not expressions?– Youjun HuApr 28 at 7:51
16 Answers
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
Statements (see 1, 2), on the other hand, are everything that can make up a line (or several lines) of Python code. Note that expressions are statements as well. Examples:
# all the above expressions
print 42
if x: do_y()
return
a = 7
-
31
-
66@bismigalis: Every valid Python expression can be used as a statement (called an "expression statement"). In this sense, expressions are statements. Nov 25, 2013 at 18:05
-
2Expressions can also include function calls (including calling classes for object instantiation). Technically these are "identifiers" exactly like names bound to values in an = statement ... even though the binding is through the 'def' or 'class' keywords. However, for this answer I would separately spell out function calls to make that clear. Feb 8, 2015 at 23:26
-
2@George Fair enough. :) Expression statements are quite useful even outside of the REPL – it's quite common to use function call expressions as expression statements, e.g.
print("Hello world!")
ormy_list.append(42)
. May 28, 2019 at 12:09 -
6@WillTaylor Everything that yields a value is an expression, i.e. everything you could write on the write-hand side of an assignment. Since
a = yield 7
is valid,yield 7
is an expression. A long time ago,yield
was introduced as a statement, but it was generalized to an expression in PEP 342. Aug 22, 2019 at 19:37
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.
In Python, expressions are covered extensively in the Python Language Reference In general, expressions in Python are composed of a syntactically legal combination of Atoms, Primaries and Operators.
Python expressions from Wikipedia
Examples of expressions:
Literals and syntactically correct combinations with Operators and built-in functions or the call of a user-written functions:
>>> 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).
Python statements from Wikipedia
In gross general terms: Statements Do Something and are often composed of expressions (or other statements)
The Python Language Reference covers Simple Statements and Compound Statements extensively.
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.
- The
if
is usually a statement, such asif x<0: x=0
but you can also have a conditional expression likex=0 if x<0 else 1
that are expressions. In other languages, like C, this form is called an operator like thisx=x<0?0:1;
- You can write you own Expressions by writing a function.
def func(a): return a*a
is an expression when used but made up of statements when defined. - An expression that returns
None
is a procedure in Python:def proc(): pass
Syntactically, you can useproc()
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 ofx=2
inside of the function call offunc(x=2)
in Python sets the named argumenta
to 2 only in the call tofunc
and is more limited than the C example.
-
3"From my Dictionary" meaning your personal opinion or the dictionary you own like the oxford dictionary ? Thanks Oct 5, 2019 at 5:13
-
3@Talespin_Kit: ...your personal opinion or the dictionary you own like the Oxford dictionary? Good question. I used the Apple Dictionary app on a Mac which is based on New Oxford American Dictionary.– dawgJan 14, 2020 at 17:30
Though this isn't related to Python:
An expression
evaluates to a value.
A statement
does something.
>>> x + 2 # an expression
>>> x = 1 # a statement
>>> y = x + 1 # a statement
>>> print y # a statement (in 2.x)
2
-
4But note that in all language except the really really "pure" ones, expressions can "do something" (more formally: have a side effect) just as well.– user395760Jan 18, 2011 at 19:32
-
5
-
14y = x + 1 is not an expression but a statement. Try eval("y = x + 1") and you'll have an error.– ArglanirFeb 4, 2013 at 9:52
-
4
-
2@SteveFreed Aren't statements made of expressions? If so, saying expression statement is rather redundant.– NamelessApr 6, 2021 at 1:14
Statements represent an action or command e.g print statements, assignment statements.
print 'hello', x = 1
Expression is a combination of variables, operations and values that yields a result value.
5 * 5 # yields 25
Lastly, expression statements
print 5*5
An expression is something that can be reduced to a value, for example "1+3"
is an expression, but "foo = 1+3"
is not.
It's easy to check:
print(foo = 1+3)
If it doesn't work, it's a statement, if it does, it's an expression.
Another statement could be:
class Foo(Bar): pass
as it cannot be reduced to a value.
-
1As executing your first example would show, assignment is not an expression (not really, that is -
a = b = expr
is allowed, as a special case) in Python. In languages drawing more inspiration from C, it is.– user395760Jan 18, 2011 at 19:26 -
class Foo(bar):
is the beginning of a statement, not a complete statement. Jan 18, 2011 at 19:28 -
1
foo = 1+3
is NOT an expression. It is a statement (an assignment to be precise). The part1+3
is an expression though.– PithikosApr 17, 2015 at 13:25 -
4My formulation is very, very precise: "If it doesn't work, it's a statement, if it does, it's an expression.". Execute it, and you'll have your answer.– FlaviusJan 31, 2017 at 7:32
-
- An expression is a statement that returns a value. So if it can appear on the right side of an assignment, or as a parameter to a method call, it is an expression.
- Some code can be both an expression or a statement, depending on the context. The language may have a means to differentiate between the two when they are ambiguous.
An expression is something, while a statement does something.
An expression is a statement as well, but it must have a return.
>>> 2 * 2 #expression
>>> print(2 * 2) #statement
PS:The interpreter always prints out the values of all expressions.
-
1
Expressions always evaluate to a value, statements don't.
e.g.
variable declaration and assignment are statements because they do not return a value
const list = [1,2,3];
Here we have two operands - a variable 'sum' on the left and an expression on the right. The whole thing is a statement, but the bit on the right is an expression as that piece of code returns a value.
const sum = list.reduce((a, b)=> a+ b, 0);
Function calls, arithmetic and boolean operations are good examples of expressions.
Expressions are often part of a statement.
The distinction between the two is often required to indicate whether we require a pice of code to return a value.
STATEMENT:
A Statement is a action or a command that does something. Ex: If-Else,Loops..etc
val a: Int = 5
If(a>5) print("Hey!") else print("Hi!")
EXPRESSION:
A Expression is a combination of values, operators and literals which yields something.
val a: Int = 5 + 5 #yields 10
-
1This is a duplicate of this existing answer: stackoverflow.com/questions/4728073/….– karelMar 9, 2019 at 15:58
-
1Maybe it's duplicate but it shares my views for the question above. No offence Mar 17, 2019 at 7:52
An expression translates to a value.
A statement consumes a value* to produce a result**.
*That includes an empty value, like: print()
or pop()
.
**This result can be any action that changes something; e.g. changes the memory ( x = 1) or changes something on the screen ( print("x") ).
A few notes:
- Since a statement can return a result, it can be part of an expression.
- An expression can be part of another expression.
References
Expressions and statements
2.3 Expressions and statements - thinkpython2 by Allen B. Downey
An expression is a combination of values, variables, and operators. A value all by itself is considered an expression, and so is a variable, so the following are all legal expressions:
>>> 42
42
>>> n
17
>>> n + 25
42
When you type an expression at the prompt, the interpreter evaluates it, which means that it finds the value of the expression. In this example, n has the value 17 and n + 25 has the value 42.
A statement is a unit of code that has an effect, like creating a variable or displaying a value.
>>> n = 17
>>> print(n)
The first line is an assignment statement that gives a value to n. The second line is a print statement that displays the value of n. When you type a statement, the interpreter executes it, which means that it does whatever the statement says. In general, statements don’t have values.
Statements before could change the state of our Python program: create or update variables, define function, etc.
And expressions just return some value can't change the global state or local state in a function.
But now we got :=
, it's an alien!
Expressions:
- Expressions are formed by combining
objects
andoperators
. - An expression has a value, which has a type.
- Syntax for a simple expression:
<object><operator><object>
2.0 + 3
is an expression which evaluates to 5.0
and has a type float
associated with it.
Statements
Statements are composed of expression(s). It can span multiple lines.
A statement contains a keyword.
An expression does not contain a keyword.
print "hello"
is statement, because print
is a keyword.
"hello"
is an expression, but list compression is against this.
The following is an expression statement, and it is true without list comprehension:
(x*2 for x in range(10))
Think of statements as consecutive actions or instructions that your program executes. So, value assignments, if clauses, together with for and while loops, are all statements. Function and class definitions are statements, too.
Think of expressions as anything that can be put into an if clause. Typical examples of expressions are literals, values returned by operators (excluding in-place operators), and comprehensions, such as list, dictionary, and set comprehensions. Function calls and method calls are expressions, too.
Python 3.8 introduced the dedicated := operator, which assigns a value to the variable but acts as an expression instead of a statement. Due to its visual appearance, it was quickly nicknamed the walrus operator.
Python calls expressions "expression statements", so the question is perhaps not fully formed.
A statement consists of pretty much anything you can do in Python: calculating a value, assigning a value, deleting a variable, printing a value, returning from a function, raising an exception, etc. The full list is here: http://docs.python.org/reference/simple_stmts.html#
An expression statement is limited to calling functions (e.g., math.cos(theta)"), operators ( e.g., "2+3"), etc. to produce a value.
-
10No, Python doesn't call expressions "expression statements". Python calls statements only consisting of a single expression "expression statements". Jan 18, 2011 at 19:37
-
... and it's not alone doing so.– user395760Jan 18, 2011 at 19:51
-
@Sven Marnach No, Python doesn't call expressions "expression statements". — Hey, but as per the EBNF rule, isn't every expression an "expression statement"? I am not sure what's wrong with calling expressions "expression statements". May 1, 2021 at 7:41
-
@NirajRaut As an example, in the assignment statement
a = 42
the right-hand side42
is an expression, but it's not an expression statement. Any expression could be used as a statement, but not every expression is actually used as a statement. May 3, 2021 at 12:49 -
@Sven Marnach Off-Topic: I have a question regarding
__init__
and__new__
. Just want to ask if a term like "constructor" exists in the Python language. I have seen that the docs use it somewhere, but I haven't seen where the term is explicitly defined. Is "constructor" part of the Python language? Does__init__
and__new__
together somehow from the constructor? You, being the pedantic guy, I would like to know your opinion on this. Also, thanks for the clarification. May 4, 2021 at 11:28