A Python expression describes a computation, or operation, performed on a data. It is the basic building block of all programs. It evaluates to a single python value and maybe using several operands.
For example, The simplest expression is simply a literal expression like 5, “h”, 1.1 etc. Name of a variable is also an expression. The arithmetic expression (5+10) describes the addition operation on 5 and 10.
An expression may contain sub-expressions: the expression (5+10) contains the sub-expressions (5) and (10). So in total, the expression (5+10) contains three different expressions (5), (10) and (5+10).
The internal representation of data in python is called a value. The evaluation of an expression results in a pythonic value.
How Python evaluates an Expression?
Evaluating an expression yields a python value. The literal expression 5 is different from the python value 5. Python evaluates an expression by first evaluating its sub-expression and using that value to evaluate the bigger expressions. The sub-expression might include further sub-expressions. This process continues until a base expression is reached.
Steps involving evaluation of a compound expression:
If one of the operands is itself an expression then it is called a compound expression. For example — (5*10 + 3–1).
Consider the example, to evaluate (5*10 + 3–1).
- Python first evaluates 5*10 to the value 50.
- Then it evaluates 3–1 to the value 2.
- Then adds the two to get 52.
Note that in order to evaluate one expression, Python evaluates several smaller expressions (such as 5*10). Furthermore, to evaluate 5*10, Python evaluates the expression 5 to the value 5, and so forth. The value of a literal expression such as 2 is the corresponding value, so this is where Python stops dividing into sub-expressions.
In general, the parenthesis is used to force the evaluation order in an expression. Since parenthesis has the highest precedence.
When more than one operator appears in an expression, the order of evaluation depends on the rules of precedence. For mathematical operators, Python follows mathematical convention. The acronym PEMDAS is a useful way to remember the rules:
- Parentheses have the highest precedence and can be used to force an expression to evaluate in the order we want. Since expressions in parentheses are evaluated first, 2 * (3–1) is 4, and (1+1)**(5–2) is 8.
- Exponentiation has the next highest precedence.
- Multiplication and Division have the same precedence, which is higher than Addition and Subtraction, which also have the same precedence.
- Operators with the same precedence are evaluated from left to right. So the expression (5–3–1) will be evaluated to 1, not 3 because (5–3) is evaluated first and then 1 is subtracted from 2.
- Exponentiation is an exception which is evaluated from right to left. So (2*32 )is 512 because it evaluates to (2(32)) and not 64 (that is (23)*2).