Precedence Rule
# Multiplication has higher precedence
# than subtraction
>>> 10 - 4 * 2
2
Associativity of Python Operators
We can see in the above table that more than one operator
exists in the same group. These operators have the same
precedence.
When two operators have the same precedence,
associativity helps to determine the order of operations.
Associativity is the order in which an expression is
evaluated that has multiple operators of the same
precedence. Almost all the operators have left-to-right
associativity.
For example, multiplication and floor division have the same
precedence. Hence, if both of them are present in an
expression, the left one is evaluated first.
# Left-right associativity
# Output: 3
print(5 * 2 // 3)
# Shows left-right associativity
# Output: 0
print(5 * (2 // 3))
Output
3
0
Note: Exponent operator ** has right-to-left associativity in
Python.
# Shows the right-left associativity of **
# Output: 512, Since 2**(3**2) = 2**9
print(2 ** 3 ** 2)
# If 2 needs to be exponated fisrt, need to use ()
# Output: 64
print((2 ** 3) ** 2)
We can see that 2 ** 3 ** 2 is equivalent to 2 ** (3 ** 2) .
Non associative operators
Some operators like assignment operators and comparison
operators do not have associativity in Python. There are
separate rules for sequences of this kind of operator and
cannot be expressed as associativity.
For example, x < y < z neither means (x < y) < z nor x < (y <
z) .
x < y < z is equivalent to x < y and y < z , and is evaluated from
left-to-right.
Furthermore, while chaining of assignments like
x = y = z = 1 is perfectly valid,
x = y = z+= 2 will result in error.
# Initialize x, y, z
x = y = z = 1
# Expression is invalid
# (Non-associative operators)
# SyntaxError: invalid syntax
x = y = z+= 2
a = 20
b = 10
c = 15
d = 5
e = 0
e = (a + b) * c / d #( 30 * 15 ) / 5
print "Value of (a + b) * c / d is ", e
In the following Expression Evaluates to always Left
>>> 25/ 5 or 2.0+20/10
5.0
>>> 2.0+20/10 or 25/5
4.0
Always left is evaluated
In case of and
>>> 25/5 and 2.0+20/10
4.0
Right is evaluated
Sample Paper ques 24
>>> 51+4-3**3//19-3
Answer :- 51
Step – 1 51+4 -27//19-3
Step -2 51+4-1-3
Step 3 51
First of all Not, and, then or is evaluated (NAR) RULE IS
Evaluate : 17>19 or 30<18 and not 19==0
EXPLAINATION
19==0 False
30<18 False
17>19 False
Now , F or F AND NOT False
NOT False = True
False or False and True
False and True = False
False
Evaluate the following expressions:
10 > 5 and 7 > 12 or not 18 > 3
Explanation:
10>5 = True
7>12 = False
18>13 = True
Now, T AND F or NOT True
T AND F = F, NOT True= F
Then, F or F=F
Ques
>>> 2+3*4//2-4
Step 1 : - 2+12//2-4
Step 2 : - 2+6-4
Answer >>4
Ques
>>> 10%3 -10//3
-2
Step 1 :- 1- 10//3
Step 2 :- 1- 3
Step 3 >>> 1-3
Answer -2
>>> 51+4-3**3//19-3
51
>>> 81//19
4
>>> 3**3
27
>>> 27//19
1
>>> 2+3*4//2-4
4
>>> 2+6-4
4
>>> 10%3 -10//3
-2
>>> 10%3
1
>>> 10//3
3
>>> 1-3
-2