Operator Precedence In Python

Hello Pythonistas😊, welcome back, today in this post we are going to explore operator precedence.

Operator Precedence

Ok, now that you know all the different types of operators in python, and what are they used for it’s time to look at their precedence.

Don’t be scared by the word it just means priority.

To be more specific which operator will be given priority when two or more are used.

An example will make this crystal clear.

print(10 - 4 * 2) #What do you think it will print? 12 or 2

It will print 2 because * has higher precedence compared to -.

I hope you got the point now. So the operator priority in python is:-

  • In the United States, we use an acronym called PEMDAS which stands for:
  • Parentheses Exponents Multiplication Division Addition Subtraction.
  • That’s the order Python follows as well.

But it is not a strict😑 order as in “Do P, then E, then M, then D, then A, and then S”.

Multiplication and division are given the same priority=).

Similarly, addition and subtraction are given the same priority=).

And among them left to right order is followed➡.

Meaning if the + sign comes before the sign then it will be a priority. Example:

print(10+2-3) #9

Internally, python will first add 10 and 2 and then, will subtract 3 from 12.

Operator Hierarchy

Operator
()
**
*, /, //, %
+, -
==, !=, >, >=, <, <=,

is, is not, in, not in
not
and
or

Leave a Reply