[Tutor] difference between expressions and statements
Ben Finney
ben+python at benfinney.id.au
Thu Apr 10 00:41:04 CEST 2014
Jared Nielsen <nielsen.jared at gmail.com> writes:
> Could someone explain the difference between expressions and
> statements?
For general programming terminology, the Wikipedia articles tend to be
good.
<URL:https://en.wikipedia.org/wiki/Expression_%28computer_science%29>
<URL:https://en.wikipedia.org/wiki/Statement_%28computer_science%29>
Roughly:
* An expression evaluates to some single value.
* A statement does some action.
> I know that expressions are statements that produce a value.
Expressions are not statements. A statement *may* be an expression.
Statements in Python can consist of an expression, or can consist of
other things.
> I'm unclear on functions and especially strings.
You're looking for a strict dichotomy which doesn't exist, and I think
that's confusing you.
> Are any of the following expressions?
They can all be statements.
> print(42)
> print("spam")
These are function calls. A function call evaluates to a value, so is
always an expression.
> spam = 42
Assignment is only a statement in Python. The statement is an
instruction to perform the assignment.
The left side is an expression evaluating to a reference; the right side
is an expression evaluating to a value.
> Is a variable assignment considered a value?
In Python, assignment (try not to think in terms of “variable”;
assignment is the act of binding a reference to a value) is always a
statement.
In other languages, assignment can return a value and is therefore an
expression. That is not the case in Python.
> Is the first example producing a value or simply displaying an
> integer?
> Does a string count as a value?
Yes to all these.
Learn more about statements – especially the fact that statements
consist sometimes of expressions alone, sometimes of other things
including expressions – at the Python Language Reference
<URL:https://docs.python.org/3/reference/expressions.html>
<URL:https://docs.python.org/3/reference/simple_stmts.html>.
--
\ “If nature has made any one thing less susceptible than all |
`\ others of exclusive property, it is the action of the thinking |
_o__) power called an idea” —Thomas Jefferson |
Ben Finney
More information about the Tutor
mailing list