Site icon DataFlair

Python Operator Precedence – PEMDAS & Short Circuiting

Python course with 57 real-time projects - Learn Python

In our last Python tutorial, we discussed Python sys Module. Today, we will see Python Operator Precedence.

Given an expression of multiple operators, how do you go about it? What is 2+3*4%5-1? 13 or 3? To answer such questions, you will need to know what comes first.

In this Python Operator Precedence tutorial, we address this issue. Moreover, we will learn PEMDAS and short-circuiting in python. At last, we will discuss the associativity of Python Operators.

So, let’s start the Python Operator Precedence tutorial.

Python Operator Precedence – PEMDAS & Short Circuiting

First, let’s revise a little about Python Operators.

Python Operator Precedence Table

Take a look at the following table of Python Operator Precedence:

Operator Description
()                    (Highest precedence) Parentheses (grouping)
f(args…) Function call
(expressions…), [expressions…], {key: value…}, {expressions…} Binding or tuple display, list display, dictionary display, set display
x[index], x[index:index], x(arguments), x.attribute Subscription, slicing, call, attribute reference
await x Await expression
** Exponentiation
+x, –x, ~x Positive, negative, bitwise NOT
*, @, /, //, % Multiplication, division, remainder
+, – Addition, subtraction
<<, >> Bitwise shifts
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
in, not in, is, is not, <, <=,  >, >=,
<>, !=, ==
Comparisons, membership, identity
not x Boolean NOT
and Boolean AND
or Boolean OR
if- else Conditional expression
lambda                  (Lowest precedence) Lambda expression

In here, the operators in one cell evaluate left to right and exponentiation groups right to left.

The lowest Precedence in Python Operator is the least binding and the highest Precedence in Python Operator is the most.

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

It is also true that we observe the same precedence for comparisons, membership tests, and identity tests. These also have a left-to-right chaining feature.

What is Python Expression?

Before we can tell you about which operator comes first, you’d want to be introduced to expressions. An expression is a combination of values, variables, operators, and function calls.

Notably, the Python interpreter can evaluate a valid expression. Why don’t we take an example?

>>> 4+3

Output

7

4+3 is an expression with one operator. We can also put in more than one. The precedence rules show us the way to follow an order. The division has a higher precedence than addition.

>>> 3+3/3

Output

4.0

When we use parentheses, however, we can alter the order of execution here.

>>> (3+3)/3

Output

2.0

What we conclude here is that using parentheses, we can force the operators of lower precedence to run first.

Or we can say that when two operators share an operand, the one with the higher precedence gets to go first.

Python Operator Precedence – PEMDAS

If you’re on this page reading about Python, you sure have heard about BODMAS somewhere in your journey so far (mathematics, school). In Python, however, we come across PEMDAS:
Parentheses
Exponentiation
Multiplication
Division
Addition
Subtraction

A mnemonic to remember that will be “Please Excuse My Dear Aunt Susie”.

Let’s take an example.

>>> ((((13+5)*2)-4)/2)-13

Output

3.0

How did that happen? Let’s work it out.
13+5 gives us 18
18*2 gives us 36
36-4 gives us 32
32/2 gives us 16.0 #Note that division gives us floats!
16-13 gives us 3.0

Python Operator Precedence – Short Circuiting

Python always evaluates the left operand before the right- even in function arguments. For expressions with and or operations, it uses short-circuiting. This means it evaluates the second operand only until it is needed. Because of this, such statements can work reliably:

Python Operator Precedence – Short Circuiting

>>> if(s!=None) and (len(s)<10): pass

To short-circuit is to stop executing the Boolean operation if we have already arrived at the truth value of the expression. Let’s take a look at this:

a. Short Circuiting with and/or

See what this gives us:

>>> 0 or "Hello" and 1

Output

1

This doesn’t give us “Hello”, but 1, because:
0 or “Hello” gives us “Hello”
“Hello” and 1 gives us 1

b. Short-Circuiting with all()/any()

This also works with the all() and any() functions.

>>> def check(i):
      return i
>>> all(check(i) for i in [1,1,0,0,3])

Output

False

This stops at the first False it gets (the 0 at the third position) and returns False.

>>> any(check(i) for i in [0,0,0,1,3])

Output

True

This stops at the first True it gets (the 1 at the fourth position) and returns True.

c. Short Circuiting with Conditional Operators

Watch how this unfurls with conditional operators like > and <.

>>> 7>8>check(4)

Output

False

This stops at 7>8 and returns False.

d. Short-Circuiting with Ternary Operators

Now, consider the following expression which is a ternary operator:

>>> print("One") if print("Two") else print("Three")

Output

Two
Three

What happens here? Let’s find out.
Python first checks the condition print(“Two”). In evaluating this, it prints “Two”. Also, the Boolean value for this is False:

>>> bool(print("Two"))

Output

Two
False

Since it is False, it does not evaluate print(“One”) and simply evaluates print(“Three”).
Hence, the final output we get is:
Two
Three

Associativity of Operators in Python

In that table above, many cells had more than one operator. These share precedence. So then, which to evaluate first?

Associativity comes to the rescue here. Many operators have left-to-right associativity.

a. Associative Operators

For an example, let’s consider the operators multiplication(*) and floor division(//). Watch how the left operand evaluates first:

>>> 3*5//4

Output

3
>>> 3*(5//4)

Output

3

While both give us the same result, they do that in different ways. Watch how:
For the first example:
3*5 gives us 15
15//4 gives us 3
For the second example:
5//4 gives us 1
3*1 gives us 3

Now, let’s try this on exponentiation:

>>> (2**3)**2

Output

64

And now without parentheses:

>>> 2**3**2

Output

512

This is because this is equivalent to:
2**(3**2)
This gives us 2**9
This gives us 512

b. Non-Associative Operators

Assignment and comparison operators are not associative. What this means is that x<y<z is none of the following:
(x<y)<z
x<(y<z)
This expression is actually equivalent to (and this evaluates left-to-right):
x<y and y<z

So, this was all in Python Operator Precedence. Hope you like our explanation.

Python Interview Questions on Operator Precedence

  1. What is operator precedence in Python?
  2. How does precedence work in Python?
  3. Which Python operator has the lowest precedence?
  4. What is the precedence of Python operators?
  5. Which Python operator has the highest precedence?

Conclusion

Hence, in this Python Operator Precedence tutorial, we learned about operator precedence, PEMDAS, and short-circuiting.

Also, we discussed expressions and associativity in Python Operator Precedence.

What would you like to read from DataFlair? Do let us know in the comments below.

Exit mobile version