Operator Precedence in Python

FREE Online Courses: Your Passport to Excellence - Start Now

Till now you would have come across many operators like addition, multiplication, etc. But what will you do when you have multiple operators in one expression?

This is the situation where we use the precedence of the operators, to get the correct result. In this article, we will learn about precedence and different other concerning concepts. So, let’s not wait and begin.

Expressions in Python

Before talking about operator precedence, first, let us know about expressions. In Python, expression can be defined as a valid combination of variables, constants, operators, and function calls. For example, look at the below example

Example of an expression in Python:

9-3

Output:

6

Here, ‘9-3’ is an expression with 9,3 as values and ‘-’ as the operator. In this example, we have only one operator. What if we have more than one operator, say a combination of +,-,*?

This is where we use precedence. Let us discuss more on this in the next section.

Python Operators precedence and the table

Let us assume, we have an expression 12+6*4. How do we evaluate it? First, we do multiplication of 6 and 4, which gives 24. Then we add 12 to 24 and the answer is 36.

Python Operator precedence

The thing that we did above is to use the concept of precedence, where we give priority to one of the operators to be used before the other. The below table gives the order, with the precedence reducing from top to bottom.

1. Operator precedence Table in Python:

Operator Description of the Operator
()                 Parentheses 
f(args…) Function call
(expressions…), [expressions…],{expressions…}, and

 {key: value…}

Displaying sequences, and

dictionaries

x[index], x[index:index], x(arguments), x.attribute Indexing, slicing, calling, attribute referencing 
await x Await expression
** Exponent
+x, –x, ~x Positive, negative, bitwise NOT
*, /, //, % Multiplication, division, remainder
+, – Addition, subtraction
<<, >> Bitwise left and right shifts
& Bitwise AND
^ Bitwise XOR
| Bitwise OR
in, not in, is, is not, <, >,<=, >=,

 !=, ==, <>

Comparisons, identity, and membership operators
not Boolean NOT
and Boolean AND
or Boolean OR
if- else Conditional expression
lambda                  Lambda expression

When we have more than one operator, the one with higher precedence will be evaluated first. From the above table, we can see that parentheses will be evaluated first and lambda at the last.

2. PEMDAS Rule in Python:

We would have learned of the BODMAS rule in mathematics while giving preference to the operators. We have a similar rule in Python and that is PEMDAS. Where,

  • P means parentheses
  • E means exponent
  • M means multiplication
  • D means division
  • A means addition
  • S means Subtraction

Let us look at some Python coding examples with some inferences.

Example of precedence of two operators:

4+6/2

Output:

7.0

Here, the first 6/2 gives 3.0. And 4+3.0 =7.0.

If we use brackets for 4+6, then the result will be.

Example of precedence of two operators on using brackets:

(4+6)/2

Output:

5.0

Now, the first 4+6 gets evaluated as it is inside the parentheses and gives 10. Then on division by 2 gives 5.0.

Example of precedence on multiple operators:

(3+6)*6-9/3+20

Output:

71.0

The flow of execution is :

  • First preference to parentheses:
    3+6=9
    => 9*6-9/3+20
  • Next preference to multiplication and division:
    9*6=54, 9/3=3.0
    =>54-3.0+20
  • Next preference to addition and subtraction:
    54-3.0=51.0
    51.0+20=71.0
  • The result=71.0

Short-Circuiting of Operators in Python

Would have heard of this in the Physics in electrical circuit chapter. But what is currently doing with operators?
Don’t worry there is no current or voltage involved here! A short circuit is a condition where the evaluation stops in between because the left half decided the result. There are 4 cases this might occur:

1. With and/ or operators in Python:

When we have an expression, say A and B, B is evaluated only if A is True. This is because if A is False, then the whole logic will be false even if B is True or False.

Similarly, if we have A or B, B will not be evaluated if A is True. Because if A is True, the whole logic will be True irrespective of B.

Let’s look at the below example.

Example of short-circuiting with and/or:

if(True or False and True):
  print("True")
else:
  print("False")

Output:

True

2. With all()/any():

The function all() stops if it first encounters any False and returns False as the result. Whereas any() stops when it first encounters True and returns True. These functions don’t check with the values further if they encounter the above cases.

Example of short-circuiting with all()

def check(i):
      return i
all(check(i) for i in [3,0,8,0,4])

Output:

False

The execution stops when first it encounters 0 (2nd element) and returns False.

Example of short-circuiting with any():

def check(i):
      return i
any(check(i) for i in [0,0,5,0,9])

Output:

True

The execution stops when first it encounters a non-zero number (3rd element) and returns True.

3. With >/< operators:

When we have two operators at a time, both the operator’s logic must be satisfied. For example, if we have A>B>C, then A>B and B>C have to satisfy.

Example of short-circuiting with conditional operators:

4>9<11

Output:

False

In the above example, 4>9 is False. Since if we have A and B, her A=4>9 and B=9<11. If A is false, the execution stops and gives False. Similarly, the execution stops after 4>9 and the output is False.

4. With Ternary operator:

Ternary operator is an operator that checks a condition and executes the main statement only if it is True. The overloading case occurs when the condition is False, where the main statement is skipped and the else part is executed.

Example of short circuiting with ternary operator:

print("a") if print("b") else print("c")

Output:

b
c

Here the boolean value of print(“b”) is False. So after executing print(“b”), print (“c”) is executed, skipping print(“a”).

Associativity of Operators

Associativity is considered where we have two or more operators of the same precedence. This decides if the evaluation of the expression has to be done from left to right or right to left based on the operator.
For almost all the operators the associativity is left-to-right, except for exponential, logical NOT and assignment operators.

Let us look at some associativity and its changes with the use of parentheses.
1. Example of associativity for + and -:

3-4+7
3-(4+7)

Output:

6-8

In the 1st case, 3-4=-1 and -1+7=6. In the 2nd case, 4+7=11 and 3-11= -8.
2. Example of associativity for * and //:

3*(4//3)

3*4//3

Output:

3

4

In the first case, 4//3 gives 1 and 3*1 is 3. In the second case, 3*4=12 and 12//3 is 4.

3. Example of associativity for exponential:

2**1**2

(2**1)**2

Output:

2

4

Exponential has the right to left associativity. In the first case, 1**2=1 gives 2**1is 2. In the second case, 2**1=2 and 2**2=4.

Non-associative operators:

Examples of non-associative operators are the assignment and comparison operators. For example a<b<c, actually check for a<b and b<c. It does not change even if we add brackets.
Similarly, chaining of assignments, a=b=c=1 is also valid.

Example of non-associative operators:

7<5<9

a=b=c=6
print(a,b,c)

Output:

False

6 6 6

However, we cannot use the other assignment operators like +=, -=, etc. This is because these variables are just created and modifications like += cannot be done.
Example of getting an error on using += in chaining:

x=y=z+=9

Output:

SyntaxError: invalid syntax

Interview Questions on Operator Precedence in Python

Q1. Are 4+3*2//3 same as (4+3)*2//3. Show using Python coding.

Ans 1. No. They are not the same. The below coding block shows this.

Example of showing the effect of brackets in Python:

4+3*2//3

(4+3)*2//3

Output:

6
4

Q2. Add parentheses in the correct location in the expression 4+6*9-3/2 to get the output as 22.0. Also, show the difference by coding.

Ans2. The parentheses should be added to 9-3 to get the answer as 22.0. The following coding block shows this

Example of adding the brackets to get desired value:

4+6*9-3/2

4+6*(9-3)/2

Output:

22.0
56.5

Q3. Change the order of the or’s, and’s to get in the expression (3<=6) and (9==0) and (5>-1) or 4 the output is True. Show different possibilities using coding.

Ans 3. Different possibilities are shown below:

Example of changing the order of and/or to get desired value:

(3<=6) and (9==0) and (5>-1) or 4

(3<=6) and (9==0) or (5>-1) and 4

(3<=6) or (9==0) and (5>-1) and 4

Output:

4
4
True

Therefore, the expression should be (3<=6) or (9==0) and (5>-1) and 4 to get the output as True.

Q4. Evaluate the following expression by interchanging the symbol of conditional operators to get True. (3>11<8>3). Show it by coding using the ‘and’ operator.

Ans 4. The expression 3>11<8>3 is evaluated as 3>11, 11<8, and 8>3. This can be changed to 3<11 and 11>8 to get True.

Example of checking the expression:

3<11>8>3
(3<11) and (11>8) and (8>3)

Output:

True
True

Q5. Evaluate the expression -5**2+34>6+8/2*3 manually and prove it using coding. Also, add braces to get a number rather than a boolean.

Ans.
-5**2+34>66+8/2*3
=-25+34>66+8/2*3 (5**2=25)
=-25+34>66+12.0 (8/2=4.0 => 4.0*3=12.0
=9>78.0 (-25+34=9 ; 66+12.0=78.0)
=False

Example of finding the result of the expression:

-5**2+34>6+8/2*3

Output:

False

The reason for getting a boolean is because of the ‘>’ operator. Whose precedence is the least? If we add brackets its precedence will be high and we get a number.

Example of adding brackets to get desired value:

-5**2+(34>6)+8/2*3

Output:

-12.0

The flow in the above expression of as follows:

  • 34>6 =>True =1 (int)
  • -5**2=-25
  • 8/2*3= 12.0
  • -25+1+12.0=12.0

Quiz on Operator Precedence in Python

Conclusion

Thus, we can conclude that we learned about precedence and associativity in the article. Along with this, we also saw some short-circuiting cases and non-associative cases.

Finally, we practiced some interview questions. Hope you learned something new from this article. Happy coding!

Your opinion matters
Please write your valuable feedback about PythonGeeks on Google | Facebook


Leave a Reply

Your email address will not be published. Required fields are marked *