Operator Precedence
Precedence represents
the priority level of the operator. The operators with higher precedence will
be executed first than of lower precedence.
Expression
|
Explanation
|
3/2*4+3+(10/4)**3-2
|
|
3/2*4+3+2.5**3-2
|
The expression in ()
is evaluated first. 10//4=2
|
3/2*4+3+15.625-2
|
Exponentiation ** is
next
|
1.5*4+3+15.625-2
6.0+3+15.625-2
|
* and /have equal
precedence, They are evaluated from left to right (Associativity). So, first
/ and then *
|
9.0+15.625-2
24.625-2
22.625
|
+ and – have equal
precedence, They are evaluated from left to right (associability). So, first
+ and then
|
Operator Precedence
Operator
|
Name
|
()
|
Parenthesis
|
**
|
Exponentiation
|
-,~
|
Unary minus (ex: -a), Bitwise complement
|
*,/,//,%
|
Multiplication,Division, floor
division(Performs division and gives only int quotient), Modulus
|
+,-
|
Addition and subtraction (Ex: a-b)
|
<<,>>
|
Bitwise left shift, Bitwise right shift
|
&
|
Bitwise AND
|
^
|
Bitwise XOR
|
|
|
Bitwise OR
|
>,>=,<,<=,==,|=
|
Relational (Comparision) Operator
|
=,%=,/=,//=,-=,+=
|
Assignment Operators
|
is, not in
|
Membership Operators
|
Not
|
Logical not
|
Or
|
Logical or
|
And
|
Logical and
|
find out the evaluation of the following expression: d=(4-2)*3**2//2+3%8
d=2*3**2//2+3%8
d=2*32//2+3%8
d=2*9//2+3%8 #Here * and // have same priority, associativity
is left to right
d=18//2+3%8
d=9+3%8
d=9+3
Ans: 12
What is Associativity in Operators?When two operators have the same precedence, associativity helps to determine which the order of operations.
Associativity is the order in which an expression is evaluated that has multiple operator 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, left one is evaluates first.
Related Video: https://www.youtube.com/watch?v=q8jc3s7Nmhk&feature=youtu.be
Next Topic: Input and output statements
Previous Topic: Bitwise XOR Operator (^)
No comments:
Post a Comment