Differencebetween an Expression and a Statement in Python

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 + 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

Expression Versus Statement

Expression: Something which evaluates to a value. Example: 1+2/x
Statement: A line of code which does something. Example: GOTO 100

In the earliest general-purpose programming languages, like FORTRAN, the distinction was crystal-clear. In FORTRAN, a statement was one unit of execution, a thing that you did. The only reason it wasn't called a "line" was because sometimes it spanned multiple lines. An expression on its own couldn't do anything... you had to assign it to a variable.

1 + 2 / X

is an error in FORTRAN, because it doesn't do anything. You had to do something with that expression:

X = 1 + 2 / X

FORTRAN didn't have a grammar as we know it today—that idea was invented, along with Backus-Naur Form (BNF), as part of the definition of Algol-60. At that point the semantic distinction ("have a value" versus "do something") was enshrined in syntax: one kind of phrase was an expression, and another was a statement, and the parser could tell them apart.

Designers of later languages blurred the distinction: they allowed syntactic expressions to do things, and they allowed syntactic statements that had values.
The earliest popular language example that still survives is C. The designers of C realized that no harm was done if you were allowed to evaluate an expression and throw away the result. In C, every syntactic expression can be a made into a statement just by tacking a semicolon along the end:

1 + 2 / x;

is a totally legit statement even though absolutely nothing will happen. Similarly, in C, an expression can have side-effects—it can change something.

1 + 2 / callfunc(12);

because callfunc might just do something useful.

Once you allow any expression to be a statement, you might as well allow the assignment operator (=) inside expressions. That's why C lets you do things like

callfunc(x = 2);

This evaluates the expression x = 2 (assigning the value of 2 to x) and then passes that (the 2) to the function callfunc.

This blurring of expressions and statements occurs in all the C-derivatives (C, C++, C#, and Java), which still have some statements (like while) but which allow almost any expression to be used as a statement (in C# only assignment, call, increment, and decrement expressions may be used as statements; see Scott Wisniewski's answer).

Having two "syntactic categories" (which is the technical name for the sort of thing statements and expressions are) can lead to duplication of effort. For example, C has two forms of conditional, the statement form

if (E) S1; else S2;

and the expression form

E ? E1 : E2

And sometimes people want duplication that isn't there: in standard C, for example, only a statement can declare a new local variable—but this ability is useful enough that the
GNU C compiler provides a GNU extension that enables an expression to declare a local variable as well.

Designers of other languages didn't like this kind of duplication, and they saw early on that if expressions can have side effects as well as values, then the syntactic distinction between statements and expressions is not all that useful—so they got rid of it. Haskell, Icon, Lisp, and ML are all languages that don't have syntactic statements—they only have expressions. Even the class structured looping and conditional forms are considered expressions, and they have values—but not very interesting ones.

What's the difference between expression and statement using Python yield

An expression can be evaluated to return a value. Any expression can also be used as a statement.

To put it another way, if you can write a = ..., then ... is an expression. So 2*3 and zip(x,y) are expressions.

Something like raise Exception is a statement but not an expression: you can't write a = (raise Exception).

yield being an expression means that b = (yield a) is valid code in a generator. If you use the generator's send() method, b is set to the value you pass in.

Difference between an Expression and Statement in Dart?

I'm still new to Dart but with previous knowledge (and reading dart language tour):

  • Expressions usually evaluate to something, for example when using conditional expression, condition ? expr1 : expr2 has a value of expr1 or expr2.
  • Statements have no value or usually do nothing to change values directly.

A statement contains expressions, but an expression can’t contain a statement.

Above is my explanation of bullet point I tried to simplify for you, found when reading language tour on category important concepts that goes like this:

Dart has both expressions (which have runtime values) and statements (which don’t). For example, the conditional expression condition ? expr1 : expr2 has a value of expr1 or expr2. Compare that to an if-else statement, which has no value. A statement often contains one or more expressions, but an expression can’t directly contain a statement.

Differences between Expression vs Function

If you think about it in the context of a pure FP, one that doesn't allow side-effects (therefore statements aren't required), then a function is a just a value with a specific type (A -> B). An expression is some combination of symbols that reduces to a value.

Consider the following examples:

a = 1 + (2 * 3);
b = a * 10;

add1 = x -> x + 1;

applyTwice = f -> x -> f(f(x))

add2 = applyTwice(add1)

a, b, add1, applyTwice & add2 are all names have been defined to hold the value computed by specific expressions. The first two expressions reduced to 7 and 70 respectively, and the latter three are function values. The final one, add2, is defined via an expression that reduces to a function value.

With regards to the points you raised:

  • A function has a name and can be referred to (though an expression could be assigned to a variable?)

Most languages allow you assign any expression to a name.

  • A function can take parameters (is an expression able to?)

Functions have parameters, unlike non-functions. As noted above, an expression can reduce to a function value.

  • A function can have a scope/encapsulation and contain multiple statements.

The function body is essentially just an expression, albeit one that contains unbound variables that reference the function parameters. Statements are a distraction - some languages also allow you to assign the result of a series of statements to a non-function variable, e.g.:

result = {
a = f();
b = g(a);
h(b);
}

(i.e. the return value of h(b) is assigned to result)

What is an expression in Python?

Expressions represent something, like a number, a string, or an instance of a class. Any value is an expression!

Anything that does something is a statement. Any assignment to a variable or function call is a statement. Any value contained in that statement in an expression.

foo = "hello" is a statement that assigns foo to the value of the expression "hello". Since the code "hello" is a simple expression, meaning it contains no operations, nothing is actually evaluated, so foo is just assigned to "hello". More complex expressions actually evaluate things, like adding numbers. Using the word expression seems like it is making things more confusing. Expressions are nothing but values, except they can have operations like addition or subtraction.

eval evaluates the string as if it were a python expression. Eval does takes an expression as an argument. However, there's nothing special about this since every single value is an expression. Saying "eval takes a value as an argument" is saying exactly the same thing, but it sounds much simpler. :D

eval( "2+2" ) passes the string "2+2" to the function. The function evaluates the expression contained in the string, which comes out to 4.

The book by Zelle says eval(<string>) evaluates string as an expression, what does that exactly mean if string is already an expression?

Any string is an expression since it represents a value. However, what is in the string has absolutely no impact on it being an expression. If its a value, its an expression. When it is "evaluated as an expression by eval", the characters inside the string are executed as if they were a python expression.

Explaining the difference between a statement and an expression in c++

Which one is correct?

Both: it is an expression statement. C and C++ let you put an expression into a body of code, add a semicolon, and make it a statement.

Here are some more examples:

x++;       // post-increment produces a value which you could use
a = 5; // Assignment produces a value
max(a, b); // Call of a non-void function is an expression
2 + x; // This calculation has no side effects, but it is allowed

Note that this is true in the specific case of C and C++, but may not be true in case of other languages. For example, the last expression statement from the list above would be considered invalid in Java or C#.



Related Topics



Leave a reply



Submit