Expressions¶

Expressions are the base unit in Python (and indeed, in most programming languages). You can think of these as similar to "terms" in a typical algebraic equation, though we'll see shortly how that analogy doesn't go very far.

Python always tries to calculate expressions to the most literal value possible. Consider putting 2 + 4 into a calculator. In this example, we don't really care about the equation 2 + 4, but rather the result. Likewise, Python cares about the result, and tries to do whatever work is required to get there -- in this case, addition.

Expressions are usually composed of other expressions; this allows us to create equations and formulas more interesting than just the two-term 2 + 4. In fact, we even consider the numbers themsevles expressions: 2 and 4 are each expressions which are composed together with the + operation to form the full expression.

In [2]:
2
Out[2]:
2
In [3]:
4
Out[3]:
4
In [4]:
2 + 4
Out[4]:
6

Python follows all of the expected order of operations in mathematics ("PEMDAS"), and evaluates inside-out, left-to-right. As such, the following two expressions result in different evaluations:

In [5]:
3 * 4 + 5 * 6
Out[5]:
42
In [6]:
3 * (4 + 5) * 6
Out[6]:
162

Given the following, how many expressions are there?

In [7]:
(72 - 32) / 9 * 5
Out[7]:
22.22222222222222
In [ ]:
(72 - 32) / (9 * 5)
In [ ]:
(72 - 32)
In [ ]:
72 - 32
In [8]:
32
Out[8]:
32
In [9]:
72
Out[9]:
72
In [ ]:
40 / 45