1.6. Operator Precedence#
What is 8/2(2+2)
?
PEMDAS: “Please Excuse My Dear Aunt Sally”
Order of precedence:
Parentheses
Exponents
Multiplication and division (left to right)
Addition and subtraction (left to right)
1.6.1. Precedence in Python#
Parentheses
Exponentiation
**
(right to left)Unary plus
+x
, unary minus-x
Multiplication
*
, division/
, floor division//
, modulo%
(left to right)Addition
+
, subtraction-
1.6.2. Ambiguity in 8/2(2+2)
#
The expression 8/2(2+2)
is ambiguous. Under standard precedence (and Python’s rules), it’s parsed as:
8 / 2 * (2 + 2)
Some readers might interpret 2(2+2)
as implicit multiplication forming a single term:
8 / (2 * (2 + 2))
To avoid ambiguity, always add parentheses to make the intended order explicit.
1.6.3. What’s potentially unclear about 212 - 32 * 5 / 9
?#
The expression is valid, but the intent may be unclear to readers. Parentheses improve readability:
212 - (32 * 5 / 9)
This makes it obvious that the multiplication and division occur before the subtraction.
1.6.4. Best practice#
Use parentheses to clarify complex expressions, even when not strictly necessary. Clear grouping improves readability and reduces errors.