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.
2
2
4
4
2 + 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:
3 * 4 + 5 * 6
42
3 * (4 + 5) * 6
162
Given the following, how many expressions are there?
(72 - 32) / 9 * 5
22.22222222222222
(72 - 32) / (9 * 5)
(72 - 32)
72 - 32
32
32
72
72
40 / 45