# Operator Precedence

When you deal with operators in Python, it is essential to understand the concept of Python operator precedence and associativity. It is because they determine the priorities of the operator otherwise we will have unexpected outputs.

## Operator Precedence

We use this in an expression that has more than one operator with difference precedence to determine which operation must be performed first.

Example

SolveÂ 25 + 10 * 20

25 + 10 * 20 is calculated as 25 + (10 * 20)

and not as (25 + 10) * 20

Code:

Python3

                    
filter_none

edit

play_arrow

brightness_4

# Precedence of '+' & '*'

expr = 25 + 10 * 20

print(expr)



Output:

                    
225



### Precedence of Python Operators

We term the combination of values, variables, operators, and function calls as an expression. The Python interpreter can evaluate a valid expression. For instance:

>>> 3 – 8

-5

Over here,Â 3 – 8Â is an expression. Thus, there can be more than one operator in an expression. Moreover, in order to evaluate these kinds of expressions, there is a rule of precedence in Python. In other words, it guides the order in which these operations carry out.

 Operators Meaning () Parentheses ** Exponent +x, -x, ~x Unary plus, Unary minus, Bitwise NOT *, /, //, % Multiplication, Division, Floor division, Modulus +, – Addition, Subtraction <<, >> Bitwise shift operators & Bitwise AND ^ Bitwise XOR | Bitwise OR ==, !=, >, >=, <, <=, is, is not, in, not in Comparisons, Identity, Membership operators not Logical NOT and Logical AND or Logical OR

For instance, multiplication has higher precedence than subtraction.

                    
# Multiplication has higher precedence

# than subtraction

>>> 10 - 4 * 2

2



However, we can change this order by making use of parenthesesÂ ()Â as it has higher precedence than multiplication.

                    
# Parentheses () has higher precedence

>>> (10 - 4) * 2

12



If you look at the operator precedence in Python in the table mentioned above, you will see it is in descending order. In other words, the upper group has higher precedence than the lower ones.

#### Example

To understand this better, we will take a look at some examples:

Suppose that you are constructing an if…elseÂ block which runsÂ ifÂ whenÂ breakfastÂ is eitherÂ cerealÂ orÂ toastÂ and only ifÂ moneyÂ is more than or equal toÂ 2.

                    
# Precedence of or & and

meal = " cerealÂ "

money = 0

if meal == " cereal" or meal == " toast" and money >= 2:

print("BreakfastÂ  being delivered")

else:

print("Can't deliver breakfastÂ ")



#### Output

                    
BreakfastÂ  being delivered



### Associativity of Python Operators

The table makes it clear that more than one operator is present in the same group. In other words, these operators have the same precedence. Thus, when two operators have the same precedence, associativity assists in determining the order of operations.

Further, we see that associativity refers to the order in which an expression is assessed that has multiple operators of the same precedence. Similarly, almost all the operators have left-to-right associativity.

For instance, multiplication and floor division have the same precedence. Therefore, if both of them exist in an expression, the left one will be 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 first, 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. Thus, we have separate rules for sequences of this kind of operator and we cannot express them as associativity.

For instance,Â 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.

In addition, 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



#### Output

                    
File "", line 8

x = y = z+= 2

^

SyntaxError: invalid syntax



## FAQ on Operator Precedence

Question 1: Which is the order of precedence in Python?

Answer 1: Python follows the same precedence rules for its mathematical operators just like mathematics.Â Further, parenthesesÂ have the highest precedence we can use them to force an expression to evaluate in the order one wants. Moreover, as we evaluate expressions first inÂ parentheses, 3 * (2-1) is 3, and (1+1)**(5-2) is 8.

Question 2: What is the precedence of logical operators?

Answer 2: The order ofÂ precedenceÂ isÂ logicalÂ complements ( Not ) are performed first. After that, logicalÂ conjunctions ( And ) are performed next. Finally, logicalÂ disjunctions ( Or ) are performed at the end.

Question 3: What is the order of operations in Python?

Answer 3: PEMDASÂ is P, E, MD, AS; multiplication and division have the same precedence, and the same applies for addition and subtraction. Further, when a divisionÂ operatorÂ appears before multiplication, division goes first. Thus, theÂ order Python operatorsÂ are executed in is governed by theÂ operatorÂ precedence, and it follows the same rules.

Share with friends

## Customize your course in 30 seconds

##### Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
Ashhar Firdausi
IIT Roorkee
Biology
Dr. Nazma Shaik
VTU
Chemistry
Gaurav Tiwari
APJAKTU
Physics
Get Started

## Browse

### One response to “Values, Variables and Keywords”

1. Brij Bhushan says:

Amazing article. Your blog helped me to improve myself in many ways thanks for sharing this kind of wonderful informative blogs in live. I also love your website because all type of information is available in your blogs. You made my day. Thanks you for everything. I have bookmarked more article from this website. Such a nice blog you are providing.