The concept of operator precedence and associativity in Python. It covers how Python interprets complex expressions containing multiple operators, provides examples of operator precedence and associativity, and discusses non-associative operators. The document also includes an operator precedence table and examples of left-to-right and right-to-left associativity.
Download Understanding Python Operator Precedence and Evaluation Order and more Lecture notes Advanced Computer Programming in PDF only on Docsity!
Python Operator Precedence and
Associativity
Riya Jacob K
Assistant Professor on Contract
Dept of Computer Applications
How does the operator precedence
work in Python?
When we group a set of values, variables, operators or function calls that turn out as an expression.
And once you execute that expression, Python interpreter evaluates it as a valid expression.
• See a simpleSee a simple exampleexample givengiven below.below.
>>> 3 + 4 7
Here, the ‘3 +4’ is a Python expression.
It contains one operator and two operands. However, a more complex statement can include multiple operators.
Operator precedence table in Python
Give examples of associativity in
Python
For example, the product (*) and the modulus (%) have the same precedence. So, if both appear in an expression, then the left one will get evaluated first.
Testing Left-right associativity
Result:Result: 11
print(4 * 7 % 3)
Testing left-right associativity
Result: 0
print(2 * (10 % 5))
As said earlier, the only operator which has right-to-left associativity in Python is the exponent (**) operator.
See the examples below.
Checking right-left associativity of ** exponent
operator
Output: 256
print(4print(4 ** 2 **** 2 ** 2)2)
Checking the right-left associativity
of **
Output: 256
print((4 ** 2) ** 2)
You might have observed that the ‘print(4 ** 2 ** 2)’ is similar to ‘(4 ** 2 ** 2).
Give examples of
nonassociative operators
For example, the expression 5 < 7 < 9 does not mean (5 < 7) < 9 or 5 < (7 < 9).
Also, the statement 5 < 7 < 9 is same as 5 < 7 and 7 < 9, and gets evaluated from left-to-right.
Moreover, chaining of assignments operators like a = b = c is perfectly alright whereas the ‘a = b += c’ will result in an error.
• ## SetSet thethe valuesvalues ofof a,a, b,b, cc x = 11, y = 12, z = 13