![]() |
VOOZH | about |
In Python, operators have different precedence levels, which determine order in which expressions are evaluated. If operators have same precedence, associativity decides whether they are evaluated left-to-right or right-to-left.
Operator precedence defines order in which Python evaluates different operators in an expression. When an expression has multiple operators, Python follows precedence rules to decide order of evaluation.
Expression:
👁 Operator-Precedence10 + 20 * 30
Example: This code shows how Python evaluates + and * operators according to precedence rules.
610
Logical operators (and, or, not) also follow precedence.
Example: This code demonstrates how and has higher precedence than or affecting conditional evaluation. Using parentheses can override default order.
Output
Hello! Welcome.Explanation:
To fix this, use parentheses:
if (name == "Alex" or name == "John") and age >= 2:
Here, parentheses ensure the or part is checked first.
Consider following list of operator precedence and associativity in Python. It shows all operators from highest precedence to lowest precedence.
Note: Parentheses () have highest precedence and can override default order. Some operators, like await and lambda, do not have associativity.
If an expression contains two or more operators with same precedence then Operator Associativity is used. It can either be Left to Right or from Right to Left.
Expression:
👁 Operator-Associativity100 / 10 * 10
Example 1: Demonstrates left-to-right associativity for division, multiplication, addition and subtraction.
100.0 6 0
Explanation:
Example 2: Demonstrates right-to-left associativity for exponentiation (**).
512
Explanation: Exponentiation (**) is evaluated right to left, so 2 ** (3 ** 2) = 2 ** 9 = 512.
Operators Precedence and Associativity are two main characteristics of operators that determine evaluation order of sub-expressions in the absence of brackets.
Expression:
👁 Operator-Precedence-and-Associativity100 + 200 / 10 - 3 * 10
Example: In this example, we calculate an expression containing addition, subtraction, multiplication and division to demonstrate how Python evaluates operators based on precedence and associativity.
90.0
In Python, most operators have associativity, which means they are evaluated from left to right or right to left when they have same precedence. However, there are a few operators that are non-associative, meaning they cannot be chained together.
Example: This code demonstrates that = and += cannot be chained because they are non-associative operators.
Output
a = b= (a < b) += (b < c)
^^
SyntaxError: invalid syntax
Explanation: = and += are non-associative; combining them in one expression causes a syntax error.