لَآ إِلَـٰهَ إِلَّا هُوَ
LA ILAHA ILLA HU
Allah, Your Lord There Is No Deity Except Him.
LA ILAHA ILLA HU
Allah, Your Lord There Is No Deity Except Him.
Lesson 10: Operator Precedence Rule In Python
Python Operators Precedence RulePython uses a rule known as PEMDAS for precedence of operators.
P – Parentheses E – Exponentiation M – Multiplication D – Division A – Addition S – Subtraction
The precedence of operators is listed from High to low.
Python Operators Precedence Table
The new Assignment expression (:=) operator from Python 3.8 onwards has the lowest precedence while parentheses() have the highest precedence.
Operator | Desription |
---|---|
:= | Assignment expression (Lowest precedence) |
lambda | Lambda expression |
if-else | Conditional expression |
or | Boolean OR |
and | Boolean AND |
not x | Boolean NOT |
<, <=, >, >=, | Comparison operators |
!=, == | Equality operators |
in, not in, is, is not, | Identity operators, membership operators |
| | Bitwise OR |
^ | Bitwise XOR |
& | Bitwise AND |
<<, >> | Left and right Shifts |
+, – | Addition and subtraction |
*, @, /, //, % | Multiplication, matrix multiplication, division, floor division, remainder |
+x, -x, ~x | Unary plus, Unary minus, bitwise NOT |
** | Exponentiation |
await x | Await expression |
x[index], x[index:index], x(arguments…), x.attribute | Subscription, slicing, call, attribute reference |
(expressions…), [expressions…],{key: value…}, {expressions…} | Binding or parenthesized expression, list display, dictionary display, set display |
() | Parentheses (Highest precedence) |
Example of Python Operators Precedence Rule
10-5 is an expression that contains a single operator.
However, an expression can also contain multiple operators and operands.
Case A
10-5/5
Output will be
9.0
In this expression, the interpreter first divided the 5/5 and then subtracted the result from 10 because,
in Python, the division operator has higher precedence than subtraction.
Case B
(10-5)/5
output will be
1.0
Explanation
Here, with the use of parentheses, we force the interpreter to first evaluate the expression
inside the parentheses and then continue the overall evaluation.