In this blog, we will learn the order of precedence in Python, which helps us to evaluate the expression values that contain multiple operators in a single expression.
Table of Contents:
Operator Precedence in Python
In Python, when we are working with expressions that contain multiple operators, then it might be difficult to understand which operator will execute first, so we must know the precedence of Python Operators.
Example:
Code:
intellipaat = 10 + 2**5
print(intellipaat)
Output:
42
Explanation: Here we have a variable intellipaat which contains an expression with multiple operators, here exponentiation operator takes precedence over the addition operator, so it will first do the exponentiation and then addition, so the output will be 42.
Python Operators Precedence Table
Let’s have a look at the below table to understand the operator’s precedence in Python:
Precedence |
Operator |
Description |
1 | () | Parentheses |
2 | a[index], a[index:index] | Slicing |
3 | await a | Await expression |
4 | ** | Exponentiation |
5 | Unary +, – (positive/negative), Bitwise NOT ~ | Unary Operator |
6 | *, /, //, % | Multiplication, division, floor division, modulus |
7 | +, – | Addition, subtraction |
8 | <<, >> | Bitwise left shift, bitwise right shift |
9 | & | Bitwise AND |
10 | ^ | Bitwise XOR |
11 | | | Bitwise OR |
12 | in, not in, is, is not, <, <=, >, >=, !=, == | Comparison operators |
13 | not x | Logical NOT |
14 | and | Logical AND |
15 | or | Logical OR |
16 | if … else | Conditional expression (ternary operator) |
17 | lambda | Lambda expression (anonymous function definition) |
Precedence of Logical Operators in Python
When we are working with logical operators in Python, as we mentioned in the above table, Logical Not takes the highest precedence, then Logical AND, then Logical OR at the last.
Example:
Code:
a = "Intellipaat"
price = 25000
if a == "Intellipaat" and price > 20000 or price < 10000:
print("This is a premium course!")
else:
print("This is an affordable course!")
Output:
This is a premium course!
Explanation: Here Logical AND and OR operator is used inside the If block, as we know AND operator has a higher precedence than OR operator, so it will execute first, and after evaluation, it returns true, therefore, if block is executed, and prints “This is a premium course!” as output.
If you want to learn more about Python Operators, you may refer our YouTube video:
Conclusion
In conclusion, Operator precedence helps us to evaluate the expression that contains multiple operators. So far in this article, we have learned, operator precedence, and its uses in the Python programming language. If you want to learn more about Python, you may refer to our Python course.