Operator precedence refers to the order in which operators are evaluated in an expression. When an expression contains multiple operators, Python follows a set of rules to decide which operator to evaluate first. The operators with higher precedence are evaluated before those with lower precedence.-13. Here’s why:*) has a higher precedence than addition (+) and subtraction (-).6 * 4 = 24.9 + 2 = 11, followed by 11 - 24 = -13.| Operator | Description |
|---|---|
(), [], {} | Parentheses, Lists, Sets, Dictionaries |
** | Exponentiation |
+, -, ~ | Unary plus, Unary minus, Bitwise NOT |
*, /, //, % | Multiplication, Division, Floor Division, Modulo |
+, - | Addition, Subtraction |
<<, >> | Bitwise Left Shift, Right Shift |
& | Bitwise AND |
^ | Bitwise XOR |
| ` | ` |
==, !=, >, <, >=, <= | Comparison Operators |
not | Logical NOT |
and | Logical AND |
or | Logical OR |
=, +=, -=, *=, /=, etc. | Assignment Operators |
** (exponentiation) has higher precedence than *, /, or +.**) and assignment operators, have right-to-left associativity, meaning they are evaluated from right to left.* and / have the same precedence, and Python evaluates them from left to right.6 * 2 = 12, then 12 / 3 = 4.0.**) has right-to-left associativity.3 ** 2 = 9, then 2 ** 9 = 512.num1 + num2 is evaluated first, resulting in 5.5 * num3 gives 20.**) has higher precedence than addition, so num1 ** num2 = 2 ** 3 = 8.8 + num3 = 8 + 4 = 12.~ operator is a bitwise NOT, and it has higher precedence than addition.~num1 converts 2 to -3 (bitwise negation), then -3 + 3 = 0.num1 * num2 and num3 + num4 are evaluated first.=) has right-to-left associativity. Therefore, num1 is assigned to num3, then num3 is assigned to num2.num2 and num3 now hold the value 5.**) has right-to-left associativity. It can be easy to think a ** b ** c is evaluated as (a ** b) ** c, but in fact, it’s evaluated as a ** (b ** c).