0% found this document useful (0 votes)
10 views6 pages

09 Precedence

The document discusses Python operator precedence and how operations in an expression are evaluated based on precedence. It provides a table of common operators from highest to lowest precedence and an example expression to demonstrate how precedence works. It recommends using parentheses to define precedence when there are multiple operators to avoid errors.

Uploaded by

Inan Garich
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views6 pages

09 Precedence

The document discusses Python operator precedence and how operations in an expression are evaluated based on precedence. It provides a table of common operators from highest to lowest precedence and an example expression to demonstrate how precedence works. It recommends using parentheses to define precedence when there are multiple operators to avoid errors.

Uploaded by

Inan Garich
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Programming using Python

Amey Karkare
Dept. of CSE
IIT Kanpur

For any queries reach out to [email protected] or [email protected]


or whatsapp 9910043510

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

Operators Description Associativity

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

• What is the value assigned to x?


x = -5*4//2*3+-1*2
-32

• ((((-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

You might also like