Operator Precedence

When an expression contains multiple operators, their evaluation order follows precedence rules: higher precedence operators are evaluated first; if precedence is equal, evaluation proceeds left to right.

For example, in 1 + 2 * 3 - 4 / 2, multiplication and division have higher precedence than addition and subtraction, so they are evaluated first.

【Excel VBA】

Table 3-9 lists the precedence of major operators in Excel VBA.

Table 3-9 Operator Precedence in Excel VBA

【Python】

Table 3-10 lists the precedence of major operators in Python.

Table 3-10 Operator Precedence in Python

Continued Table 3-10

Examples of Precedence

Arithmetic Operations

Evaluate multiplication/division before addition/subtraction:

Excel VBA:

code.vba
Debug.Print 1 + 2 * 3 - 4 / 2  ' Output: 5

Python:

code.python
>>> 1 + 2 * 3 - 4 / 2

5.0 # Float result due to division

Parentheses Override Precedence

Use parentheses to change evaluation order:

Excel VBA:

code.vba
Debug.Print((1 + 2) * 3 - 4) / 2  ' Output: 2.5

Python:

code.python
>>> ((1 + 2) * 3 - 4) / 2
2.5

Relational and Logical Operations

Evaluate relational operations before logical operations:

Excel VBA:

code.vba
Debug.Print 3 > 2 And 7 < 5  ' Output: False

Python:

code.python
>>> 3 > 2 and 7 < 5
False

In the above example:

3 > 2 returns True, 7 < 5 returns False.

True and False returns False.