Skip to content

Informatics Practices · Ch 3 — Brief Overview of Python

Expressions

3.7

Expressions

Constants store fixed values, variables store changeable ones, and operators act on them — an expression is where all three come together. An expression is defined as a combination of constants, variables and operators. Its defining property is this: an expression always evaluates to a value. Whatever mixture of numbers, names and symbols you write, if it is a valid expression, Python can boil it down to a single resulting value.

What counts as an expression — and what does not

The definition is more generous than it first appears:

  • A value standing alone is an expression. The constant 3.14 by itself evaluates to a value (itself), so it qualifies.
  • A standalone variable is also an expression — a variable name on its own evaluates to whatever value it currently holds.
  • A standalone operator, however, is not an expression. A bare + or * has nothing to work on and evaluates to nothing; operators only gain meaning when they are given operands.

That single test — "does it evaluate to a value?" — separates expressions from non-expressions.

Examples of valid expressions

Each of the following is a valid expression, since each one reduces to a single value:

num - 20.4
3.0 + 3.14
23/3 - 5 * 7 * (14 - 2)
"Global" + "Citizen"

A few observations about these examples:

  • num - 20.4 mixes a variable with a constant; its value depends on what num holds at that moment.
  • 3.0 + 3.14 combines two constants and evaluates to their sum.
  • An expression may chain several operators and parentheses together, as in the third example — division, subtraction and multiplication in one line still produce a single value.
  • "Global" + "Citizen" shows that expressions are not restricted to numbers: here + concatenates two strings, and the expression evaluates to the string 'GlobalCitizen'.
Important

An expression always evaluates to a value. A value or a standalone variable is itself an expression, but a standalone operator is not. …