09 Precedence
09 Precedence
Amey Karkare
Dept. of CSE
IIT Kanpur
1
Welcome Python Programming
Operator Precedence
2
Recap
• Python program is a sequence of commands
• Commands manipulate objects
• Objects have types
• Commands contain operations
– Arithmetic, Logical, Relational,…
• Multiple operations are possible in a single command
– How to resolve the operands for each operator?
3
10/27/2016 Programming
Operator Precedence
• More than one operator in an expression
– Identification of the arguments is based on
precedence
• Parenthesis (…) have the highest precedence
• Precedence order for some common operators
coming next
• Consult any textbook to know about precedence
of remaining operators
4
10/27/2016 Programming
Operator Precedence
HIGH
(unary) + - Unary plus/minus Right to left
I
N * / % // Multiply, divide, remainder, integer div Left to right
C
R +- Add, subtract Left to right
E
A < > >= <= less, greater comparison Left to right
S
I == != Equal, not equal Left to right
N
G = Assignment Right to left
LOW
5
10/27/2016 Programming
Operator Precedence
• ((((-5)*4)//2)*3) + ((-1)*2)
• Easy to get precedence wrong. Avoid relying on
operator precedence. Can give absurd results if
not used correctly.
• When in doubt, use parenthesis to define
precedence. It is safer and easier to read.
• Consult any book/online documentation to know
more about precedence.
6
10/27/2016 Programming