In Python, the rules of precedence determine the order in which operators are evaluated in expressions. Operators with higher precedence are evaluated before operators with lower precedence. Python follows the same rules of precedence as mathematics.
The following table shows the order of precedence for Python's arithmetic operators:
| Operator | Description | | -------- | ----------- | | ** | Exponentiation | | * / % // | Multiplication, division, modulus, floor division | | + - | Addition, subtraction |
It's important to note that Python also supports parentheses to group sub-expressions that should be evaluated first.
Here's an example of how the rules of precedence work in Python:
main.py59 chars3 lines
In the example above, the exponentiation operator (**
) has the highest precedence, so 4 ** 2
is evaluated first, resulting in 16
. Next, the modulus operator (%
) and the floor division operator (//
) have the same precedence and are evaluated left-to-right, so 16 % 3
is evaluated first, resulting in 1
, and then 1 // 2
is evaluated, resulting in 0
. Finally, the multiplication operator (*
) and the addition operator (+
) have the lowest precedence and are evaluated left-to-right, so 3 * 0
is evaluated first, resulting in 0
, and then 2 + 0
is evaluated, resulting in 2
. Therefore, the final value of result
is 2
.
gistlibby LogSnag