Operator Precedence in Python Programming
Operators in Python
In this lesson, we will learn what is the rule of Operator Precedence in Python programming and how it works with some examples.
What is Operator Precedence
Operator Precedence in Python programming is a rule that describe which operator is solved first in an expression. For example: * and / have same precedence and their associativity is Left to Right, so the expression 18 / 2 * 5 is treated as (18 / 2) * 5.
Let's take another example say x = 8 + 4 * 2 here value of x will be 16 and not 24 why, because * operator has a higher precedence than + operator. So 4*2 gets multiplied first and then adds into 8.
Operator Associativity means how operators of the same precedence are evaluated in an expression.
The table below shows all the operators in Python with precedence and associativity.
Precedence of Operators in Python
|~ + -||Unary Bitwise NOT, Unary Plus, Unary Minus|
|+ -||Addition, Subtraction|
|<< >>||Bitwise leftshift and right shift|
Greater then or equal to
Less then or equal to
Not equal to
|is, is not
in, not in
|and or not||Logical Operators|
Please don't get confused after seeing the above table. They all are used in a different situation but not all at the same time. For solving basic equation we will consider the following operator precedence only.
- ( ) Brackets will be solved first.
- * / % // Which ever come first in your equation.
- + - Which ever come first in your equation.
Now let's see some examples for more understanding.
45 % 2 + 3 * 2 45 % 2 + 3 * 2 will be solved as per operator precedence rule 1 + 3 * 2 will be solved as per operator precedence rule 1 + 6 will be solved as per operator precedence rule 7 (Answer)
19 + (5 / 2) + 4 % 2 - 6 * 3 19 + (5 / 2) + 4 % 2 - 6 * 3 will be solved as per operator precedence rule 19 + 2.5 + 4 % 2 - 6 * 3 will be solved as per operator precedence rule 19 + 2.5 + 0 - 6 * 3 will be solved as per operator precedence rule 19 + 2.5 + 0 - 18 will be solved as per operator precedence rule 21.5 + 0 - 18 will be solved as per operator precedence rule 21.5 - 18 will be solved as per operator precedence rule 3.5 (Answer)