4

Possible Duplicate:
Expression Versus Statement

What's the difference between expression and statement in Python?

I have never thought of this question until I am learning Python generator that said "use yield as an expression"

Also, can you explain this question in the context of Python generator that 'use yield as an expression'?

Community
  • 1
  • 1
ming.kernel
  • 3,365
  • 3
  • 21
  • 32
  • I find the original question's answer pock-marked with enough exceptions to be almost useless. I view the answer given by ThomasK (below) as an improvement. Would changing the title of this question to "What's the difference between expressions and statemets in Python" be sufficient to allow re-opening? – JS. Sep 26 '12 at 18:07
  • @JS.I think you are right; I just saw the original answer. – ming.kernel Sep 27 '12 at 01:48

3 Answers3

8

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.

Thomas K
  • 39,200
  • 7
  • 84
  • 86
2

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.

Statements 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.

Hope it will help you :)

user786
  • 383
  • 1
  • 3
  • 15
0

I'd distill it down to this:

  • an expression is something--as has been said, it has a value--and
  • a statement does something.

Of course, the problem with all reductions of this kind is that there's a caveat; an expression may still do something as part of its evaluation. But it still has a value in the end.

Mattie
  • 20,280
  • 7
  • 36
  • 54