Technicalstatements and expressions Seeing the difference

STUFF

Python code consists of statements and expressions. Knowing these terms isn't essential to writing basic code, but sometimes they help you to understand an error in your code (for example, you can't use a statement where an expression is required).

A literal is a chunk of text in a Python program that specifies the value for one of the basic Python data types (such as a string or number). When you run your program, Python creates an object with the literal's value.

A statement is like a command—it tells Python to do something. For example, the statement x = 2 5 tells Python to give the name x to the value 2 5, and print x tells Python to display the value of x.

An expression is one or more operations that produce a result. The operations can involve names, operators, literals, and function or method calls.

It's easiest to show the difference between expressions and statements by example. Note in these examples that when you enter an expression in the interpreter, the interpreter prints it, but when you enter a statement(which doesn't create any output—except for print statements), nothing visible happens:

>>> "monty python"

#

This

is

an expression and a

literal.

'monty python'

>>> x = 25

#

This

is

a statement. 25 is a

literal.

>>> x

#

This

is

an expression.

25

>>> 2 in [1, 2, 3]

#

This

is

also an expression.

True

>>> def foo():

#

This

is

a statement.

... return 1

#

return

is a statement; 1 is an

expression.

>>> foo()

#

foo

is

a name; foo() is an

expression. 1

expression. 1

Note that Python allows you to put multiple statements on a line by separating each statement with a semicolon, but you should avoid this because it makes programs less readable:

Was this article helpful?

0 0

Post a comment