Order of operationsΒΆ
- The order of evaluation depends on the rules of precedence.
- Python follows the same precedence rules for its mathematical operators that mathematics does.
- The acronym PEMDAS (or PEDMSA) is a useful way to remember the order of operations:
Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want.
2 * (3-1)
is 4.Exponentiation has the next highest precedence, so``3*1**3`` is 3.
Multiplication and both Division operators have the same precedence, which is higher than Addition and Subtraction, which also have the same precedence. So
2*3-1
yields 5.Operators with the same precedence are evaluated from left-to-right. In algebra we say they are left-associative. So
6-3+2
yields 5.- Due to some historical quirk, an exception to the left-to-right left-associative rule is the exponentiation operator
**
- always use parentheses to force exactly the order you want when exponentiation is involved:
- Due to some historical quirk, an exception to the left-to-right left-associative rule is the exponentiation operator