Python Module 5 Assco Prece
Python Module 5 Assco Prece
Precedence &
associativity
in
Python
Precedence Operator
wHat is Precedence
Operator?
()
• Operator precedence is used to determine the
order of operators evaluated in an expression.
**
• Every operator has precedence (priority).
*
/
Precedence Operator
wHat is Precedence
Operator?
() • If more than one operator is used in an expression,
the higher precedence operator is evaluated first
and the operator with the least precedence is
** evaluated last.
Example
* A=1
B=2
/ C=3
Answer = a + b *c (We assume that (1+2)*3) = 9)
Output = a+ b * c (But Computer evaluates in the
order 1 + (2 *3) = 7)
PEMDAS
() wHat is
() PEMDAS?
**
**
/ The acronym PEMDAS (Parentheses, Exponentiation,
Multiplication, Division, Addition, Subtraction) 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 you want.
● Since expressions in parentheses are evaluated
- first, 2 * (3-1) is 4
and (1+1)**(5-2) is 8.
PEMDAS
() wHat is PEMDAS?
**
● Exponentiation has the next highest precedence,
* so 1 + 2**3 is 9, not 27
/ And 2 *3**2 is 18, not 36.
● Multiplication and Division have higher
+ precedence than Addition and Subtraction. So
2*3-1 is 5, it's not 4
- And 6+4/2 is 8, it's not 5.
PEMDAS
1 + 2 ** 3
Exponentiation
will happen first
1 + 8
Now addition will
happen
9
Operator precedence
Precedence Operator Operator Meaning
1 () Parenthesis Or Function Call
2 ** Exponentiation
+x Unary Plus
3 -x Unary Minus
~x Bitwise Negation
* Multiplication
/ Division
4
// Floor Division
% Modulus
+ Addition
5
- Subtraction
<< Left Shift
6
>> RIght Shift
Operator precedence
Precedence Operator Operator Meaning
7 & Bitwise AND
8 ^ Bitwise XOR
9 | Bitwise OR
== Equal to
!= Not Equal to
< Less Than
<= Less Than or Equal to
10 > Greater Than
>= Greater Than Equal to
is Identity Operator
is not Identity Operator
Operator precedence
Precedence Operator Operator Meaning
11 not Boolean NOT
12 and Boolean AND
13 Boolean OR
or
LMS Activity
Order of Evaluation/ Associativity
wHat is Operator
Associativity?
Note
Almost all operators except the exponent (**)
support the left-to-right associativity.
Order of Evaluation/ Associativity