Skip to content
Home » Precedence of Operators in Python

Precedence of Operators in Python

Spread the love

Today we’ll be talking about the precedence of operators.

Here’s the video version of this article:

Some operators are more important than others, at least in terms of precedence. Here we have all the operators from highest to lowest precedence:

1()Parentheses
2**Exponentiation
3~ + Complement Unary Plus Unary Minus
4* / // %Multiplication True Division Floor Division Modulus
5+ Addition Subtraction
6>> << Right Bitwise Shift Left Bitwise Shift
7&Bitwise AND
8^Bitwise Exclusive OR (XOR)
9|Bitwise OR
10 <= > >=Comparison Operators  
11== !=Equal To Not Equal To
12= += -= *= /= //= %= **=Assignment Operators
13is is notIdentity Operators
14in not inMembership Operators
15notLogical not
16andLogical and
17orLogical or

Operators with higher precedence work first, so for example in the following example first 3 and 2 are multiplied and then the product is added to 7. This is because multiplication is higher in the precedence hierarchy than addition.

>>> 7 + 3 * 2
13 

Now a totally different example:

>>> 3 ** 2 * 5 % 2 // 4 / 2 <= -1 * 2
False 

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Let’s analyze it step by step:

Of all the operators here exponentiation is the one with the highest precedence. It’s carried out first. Now we have:

9 * 5 % 2 // 4 / 2 <= -1 * 2

The next in the hierarchy is the unary minus, so we have a negative 1:

9 * 5 % 2 // 4 / 2 <= (-1) * 2

And then we have multiplication, true division, floor division and modulus, all on the same level in the hierarchy, so they are used in the order of appearance:

0.0 <= -2

which is false.

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Use Parentheses

It’s extremely easy to lose track of what’s going on and in which order with such complicated expressions. That’s why we should use parentheses as much as possible. They are the highest in the precedence hierarchy. It’s advisable to use them even if it’s not necessary, just to make it clearer.

Here are a few expressions with parentheses in different places. The result is different each time because the operators are applied according to the placement of the parentheses:

>>> 5 + 2 ** 3 / 3
7.666666666666666
>>> (5 + 2) ** 3 / 3
114.33333333333333
>>> 5 + 2 ** (3 / 3)
7.0
>>> (5 + 2 ** 3) / 3
4.333333333333333
>>> (5 + 2) ** (3 / 3)
7.0 

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply