2. Basic Types: Booleans
Precedence and Associativity
Now that we have seen simple boolean logic using the
Simply chaining operators and booleans:
>>> 1 and 1 and 1
|
1
|
>>> 1 and 1 and 0
|
0
|
However, chaining would be very limited if there wasn't a way to modify the evaluation order of sub-expressions. The order of evaluation is determined by operator precedence and associativity. Luckily there is a way to bend the order to our will: parentheses. We can use parentheses to assign priority to certain sub-expressions, just like we would in mathematics.
PrecedenceOperator precedence or order of operations is a collection of rules that reflect conventions about which procedures to evaluate first in a given expression.
In math and in Python, multiplication has precedence over summation, i.e. the
In Python boolean logic, the precedence of the three discussed operators goes:
>>> 1 or 1 and 0
|
1
|
The subexpression
>>> not 1 or 1
|
1
|
The subexpression
>>> (1 or 1) and 0
|
0
|
Now, the subexpression
>>> not (1 or 1)
|
False
|
Here, the subexpression
But what happens to the order of operations when we have an expression with two of the same operators? That is where associativity comes into play.
AssociativityThe associativity of an operator is a property that determines in what order operators of the same precedence are grouped and evaluated in the absence of parentheses.
We recognise four distinct types of associativity: associative, left-associative, right-associative and non-associative. Associative operators can be grouped arbitrarily, left- and right-associative operators are grouped from the left or right respectively and non-associative operators cannot be chained at all. Both associativity and precedence are part of the definition of a programming language, as a result they can differ between programming languages.
In Python, almost all operators are left-associative, this includes
Because
>>> 7 - 4 + 2
|
5
|
If
>>> 7 - (4 + 2)
|
1
|
In the upcoming theory pages we will see that not all Python operators are left-associative.
Or visit omptest.org if jou are taking an OMPT exam.