Computer Science · Ch 5 — Getting Started with Python
Expressions
5.9
Expressions
An expression is a combination of constants, variables and operators. The defining property of an expression is that it always evaluates to a value — Python works it out and produces a single result.
Two boundary cases complete the definition:
- A value on its own (like
100) or a standalone variable (likenum) is also considered an expression — it trivially evaluates to itself (or to the value it holds). - A standalone operator is not an expression —
+or*by itself has nothing to operate on and produces no value.
Examples of valid expressions
100 # a value alone is an expression
num # a standalone variable is an expression
num - 20.4 # variable combined with a constant
3.0 + 3.14 # two constants and an operator
23/3 - 5 * 7 * (14 - 2) # a longer arithmetic expression
"Global" + "Citizen" # a string expression - evaluates to 'GlobalCitizen'
Each of these, when typed at the interpreter prompt, is evaluated down to one value:
>>> 3.0 + 3.14
6.[PII:card]
>>> "Global" + "Citizen"
'GlobalCitizen'
Notice that expressions are not limited to numbers — the last example is a string expression, where + acts as the concatenation operator and the result is a new string. …