What is an expression in Python?
Asked Answered
G

4

20

I have some confusion about its meaning or definition.

Isn't that some code that produce or calculate new data values? (Says Zelle in his book)

Then I wonder if a string data type is an expression.

If it is, then what does eval() do when its argument is a string?

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

And if string is not an expression, then how come it can occur after print?

Getty answered 24/1, 2011 at 13:34 Comment(2)
Related (but not an exact duplicate): What is the difference between an Expression and a Statement?Molini
By far the most clear definition of the term applicable to all programming languages including python from Foldoc - Free Online Dictionary of ComputingStrephonn
S
32

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.

Swiftlet answered 24/1, 2011 at 13:40 Comment(5)
Good explanation, except that you can't eval statements: try eval("print hello") in Python 2.x.Creamery
A function call is an expression in Python. An any expression is also a statement -- an "expression statement". See also the link to the related question I gave above.Molini
@Sven I'm using a different definition of an expression for simplicity's sake. I figured leaving that information out would avoid extra complexity, especially since expressions as statements aren't very widely used. :DSwiftlet
There is actually an "official" definition of what an expression in Python is (basically everything that can be evaluated by eval()). And since every function call on a line of its own is an expression statement, they are very widely used. I don't see why being correct adds complexity here.Molini
It may be interesting to note that an assignment can not be performed in an expression in python which avoids if (a = 4) vs if (a == 4) bugs. eval("a=4") for example is a syntax error.Trinitrophenol
M
5

TL;DR: Expressions are combinations of values and operators and always evaluate down to a single value. A statement is every other instruction. Some statements contain expressions.

An expression is an instruction that combines values and operators and always evaluates down to a single value.

For example, this is an expression:

>>> 2 + 2

The 2s are integer values and the + is the mathematical operator. This expression evaluates down to the single integer value 4.

Technically, this is also an expression:

>>> 4

As an expression, it evaluates down to the single value 4.

When I say values and operators, this isn't limited to math problems:

>>> 'You will be ' + str(int(myAge) + 1) + ' next year.'

The myAge variable evaluates to the value inside it. The function call int('5') evaluates to the function's return value, 5. All these string values are combined with the + operator (in this case, it's the string concatenation operator). No matter how big an expression is, it evaluates down to a single value: in this case, the string value 'You will be 6 next year.'

Contrast this with a statement, which is a Python instruction that does not evaluate down to a value. A Python statement is pretty much everything else that isn't an expression. Here's an assignment statement:

>>> spam = 2 + 2

Here's an if statement:

>>> if spam == 4:

Here's a while statement for an infinite loop:

>>> while True:

Note that both of these statements contain expressions (even True, which evaluates down to the single value True). But not all statements use expressions in them. Here's a break statement:

>>> break
Merri answered 8/5, 2015 at 1:11 Comment(0)
P
3

"Expression" can be a slightly confusing term once you get away from thinking about how Python's own script parser works. The standard documentation makes a distinction between expressions and "atoms", but I think that makes its terminology pretty restrictive (the BNF diagram at 5.11 implies that to be an expression something must be either a lambda form or a conditional expression, I think. My BNF is rusty.)

Atoms, on the other hand, seem to cover as @kynnysmatto says 'anything that has "a value"'. Maybe "anything that can be parenthesized, and then from outside the parentheses is indistinguishable from its corresponding value" might be a better definition of an atom.

When Zelle discusses expressions in the context of e.g. eval(foo), I think he implies:

  • foo is an identifier, which is a type of atom
  • but foo is an identifier of something
  • this "something" is string-like, probably an actual string
  • within the internals of eval(), this string also constitutes a Python "expression" - that is, something Python can parse and make sense of.

tl;dr: "expression" as terminology might be best understood in terms of code parsing; when you program yourself, you might find it better to think in terms of "atoms".

Prophesy answered 24/1, 2011 at 14:2 Comment(0)
Q
1

string is an expression. An expression is anything that has "a value". Like 3, 'Hello world', 1+1, math.sqrt(9), etc. Function names are expressions too.

eval() gives you the value of the expression that you give to it as a string. If you say eval('1+1') it returns 2. So it returns the same that would be returned if you simply write: 1+1.

Queenstown answered 24/1, 2011 at 13:39 Comment(3)
In addition to that: Every method/function that returns a value counts also as an expression. So eval itself is an expression a well for example.Diesis
@poke: That's kind of misleading. Every method/function returns a value. If you don't return anything explicitly, it implicitly returns None. (Of course in practice, a particular function call might raise, sys.exit, spin forever in an infinite loop, etc. instead of returning. But that doesn't make that function call expression not an expression, any more than 1/0.)Neap
@Neap Hard to say now what I meant back then, but I think I meant that all those things count as an expression as well, not just the standard static ones with some basic operator in between.Diesis

© 2022 - 2024 — McMap. All rights reserved.