Python operator precedence determines the order in which operators are evaluated in expressions. Understanding this concept is crucial for writing correct code and acing technical interviews and exams like EMRS, KVS, NVS, HPSC TGT/PGT CS, CBSE Class 11 & 12, ISC, BCA, MCA, and B.Tech.
Key Operator Groups and Precedence (Highest to Lowest)
- Parentheses
()– Override default precedence. - Exponentiation
**– Right-associative. - Unary operators
+,-,~– Unary plus, minus, bitwise NOT. - Multiplication, Division, Floor Division, Modulus
*,/,//,% - Addition and Subtraction
+,-(binary) - Shift operators
<<,>> - Bitwise AND
& - Bitwise XOR
^ - Bitwise OR
| - Comparison operators
==,!=,>,<,>=,<=,is,in, etc. - Logical NOT
not - Logical AND
and - Logical OR
or
Associativity
Most operators are left-associative (evaluated left to right), except exponentiation ** which is right-associative.
Tricks for Output-Based Questions
- Always evaluate expressions inside parentheses first.
- Remember that
**has higher precedence than unary minus:-2**2evaluates to-4(not4). - Bitwise operators have lower precedence than arithmetic but higher than comparisons.
- Logical operators
and/orshort-circuit:False and anythingreturnsFalsewithout evaluatinganything.
Example
result = 2 + 3 * 4 ** 2 # 2 + 3 * 16 = 2 + 48 = 50
print(result) # Output: 50
For comprehensive preparation, watch the full video tutorial by Saurabh Chauhan (SaurabhTechStudio) and practice with exam-oriented questions.