In Python, what is the difference between expressions and statements?
-
4Due to python's definition that expressions are a subset of statements, the question can be revised as: which statements are not expressions?Youjun Hu– Youjun Hu2022年04月28日 07:51:29 +00:00Commented Apr 28, 2022 at 7:51
19 Answers 19
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
17 Comments
print("Hello world!") or my_list.append(42).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.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
15 Comments
somelist.append(123). Most function calls, really.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
ifis usually a statement, such asif x<0: x=0but you can also have a conditional expression likex=0 if x<0 else 1that 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*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 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=2inside of the function call offunc(x=2)in Python sets the named argumentato 2 only in the call tofuncand is more limited than the C example.
3 Comments
for, can we really say that a list comprehension contains a for statement ? I don't think so. Similarly, just because a conditional expression uses the keyword if, I don't think that we can say that a conditional expression contains an if statement and is therefore "blurring" the distinction between statement and expression.An expression is something that can be reduced to a value.
Let's take the following examples and figure out what is what:
"1+3" and "foo = 1+3".
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. Try it out!
Another statement could be:
class Foo(Bar): pass
as it cannot be reduced to a value.
7 Comments
foo = 1+3 is NOT an expression. It is a statement (an assignment to be precise). The part 1+3 is an expression though.foo=1+3 as a keyword argument, which is not expected by the print function.print(end="1+3") works, but end="1+3" is neither an expression nor a statement (though it looks like a statement, it's just part of the syntax of a function call.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
1 Comment
print is an ordinary function now, not a statement.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.
4 Comments
- 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.
Comments
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
3 Comments
pass is a statement. It is neither an action nor does it do anything. 5 + 5 is an expression; a = 5 + 5 is not. (val is just a syntax error in both cases.)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.
Comments
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.
Comments
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.
5 Comments
pass is a statement: it does not consume a value or produce a result.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!
1 Comment
:= just allows names to be bound in value outside of a function, which previously was the only way to wrap an assignment into an expression.Expressions:
- Expressions are formed by combining
objectsandoperators. - 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.
Comments
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))
Expressions are evaluated to produce a value, whereas statements are executed to perform an action or task.
1 Comment
Expressions and statements are both syntactic constructs in Python's grammar.
An expression can be evaluated to produce a value.
A statement is a standalone piece of a Python program (which is simply a sequence of 0 or more statements, executed sequentially). Each kind of statement provides a different set of semantics for defining what the program will do.
Statements are often (but not always) constructed from expressions, using the values of the expressions in their own unique way. Usually, there is some keyword or symbol that can be used to recognize each particular kind of statement.
An exhaustive (as of Python 3.11) list of the various kinds of statements.
- An expression statement evaluates an expression and discards the result. (Any expression can be used; there are no other distinguishing features of an expression statement.)
- An assignment statement evaluates an expression and assigns its value to one or more targets. It is identified by the use of
=outside of the context of a function call. - An assert statement evaluates an expression and raises an exception if the expression's value is false. It is identified by the
assertkeyword. - A pass statement does nothing: it's job is to provide the parser with a statement where one is expected but no other statement is appropriate. It is identified by (and consists solely of) the
passkeyword. - A del statement removes a binding from the current scope. No expression is evaluated; the binding must be a name, an indexed name, or a dotted name. It is identified by the
delkeyword. - A return statement returns control (and the value of an optional expression, defaulting to
None) to the caller of a function. It is identified by thereturnkeyword. - A yield statement returns the value of an optional expression (defaulting to
None) to the consumer of a generator. It is identified by theyieldkeyword. (yieldis also used in yield expressions; context will make it clear when a statement or expression is meant.) - A raise statement evaluates an expression to produce an exception and circumvents the normal execution order. It is identified by the
raisekeyword. - A break statement terminates the currently active loop. It is identified (and consists solely of) the
breakkeyword. - A continue statement skips the rest of the body of the currently active loop an attempts to start a new iteration. It is identified (and consists solely of) the
continuekeyword. - An import statement potentially defines a new
moduleobject and binds one or more names in the current scope to either amoduleor values defined in the module. (Like theclassstatement, there are various hooks available to override exactly what happens during the execution of an import statement.) There are several forms, all of which share theimportkeyword. - A global and nonlocal statement alters the scope in which an assignment to a particular name operates. They are identified by the
globalandnonlocalkeywords, respectively. - An if statement evaluates a boolean expression to select a set of statements to execute next. It is identified by the
ifkeyword. - A while statement evaluates a boolean expression to determine whether to execute its body, repeating the process until the expression become false. It is identified by the
whilekeyword`. - A for loop evaluates an expression to produce an iterator, which it uses to perform some name bindings and repeatedly execute a set of statements with those bindings. It is identified by the
forkeyword (which is also shared by generator expressions and comprehensions, though context makes it clear which is which). - A try statement executes a set of statements and catches any exceptions those statements might raise. It is identified by the
trykeyword. - A with statement evaluates an expression to produce a context manager, which provides a pair of functions to call before and after a set of statements is executed. It is identified by the
withkeyword. - A function definition produces a callable object that wraps one or more statements to be execute when the object is called. It is identified by the
defkeyword. - A class statement evaluates a set of statements to produce a set of bindings to be used as attributes of a new type. (Like an import statement, there are various hooks to override exactly what happens during the execution of a class statement.) It is identified by the
classkeyword. - Coroutines are produced by various function, for, and with statements using the
asynckeyword to distinguish them from their synchronous counterparts.
Comments
Statements are made up of one or more expressions. An expression is any reference to a variable or value, or a set of variable(s) and value(s) combined with operators.
For example:
a = b * 2;
This statement has four expressions in it:
2is a literal value expression.bis a variable expression, which means to retrieve its current value.b * 2is an arithmetic expression, which means to do the multiplication.a = b * 2is an assignment expression, which means to assign the result of theb * 2expression to the variablea.
A general expression that stands alone is also called an expression statement, such as the following:
b * 2;
This flavor of expression statement is not very common or useful, as
generally, it wouldn’t have any effect on the running of the program, it would retrieve the value of b and multiply it by 2, but then
wouldn’t do anything with that result.
A more common expression statement is a call expression statement, as the entire statement is the function call expression itself:
print(a)
reference: You Don't Know JS - Up & Going
Comments
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.
13 Comments
a = 42 the right-hand side 42 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.__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.For someone who is new to python, I would say that easiest way to understand and determine whether something is expression or statement is to try with "print()" built-in function.
- Statements being actions or commands cannot be printed directly.
- Expression "producing" values can be printed.
Example:
def sum(a, b):
return a+b
print(sum(2,3))
So the output would be 5, therefore we can say that functions are indeed expressions.
When basics is understood it is easier to dig deeper into topic.
1 Comment
print call, you'll get a syntax error. That's the real difference.