2.3.6 Operator Precedence in Python
Python Programming
Operator precedence determines the order in which operations are performed in an expression. In Python as well as in Mathematics, certain operators have higher precedence and are evaluated before others. Understanding this helps ensure that your calculations are done correctly.
- Parentheses '()': Highest precedence. Operations inside parentheses are performed first. (3 + 2) * 4 evaluates to 20.
- Exponentiation: Performs power operations next.
- 2³ evaluates to 8.
- Multiplication '*', Division '/', and Modulus '%': These operations come next. 4*3 evaluates to 12, 10/2 evaluates to 5.0 and 11%3 evaluates 2.
- Addition '+' and Subtraction '-': These have lower precedence compared to multiplication and division.
- 5 + 2 evaluates to 7, and 10-4 evaluates to 6.
- Example: Consider the expression 3 + 2*5. The multiplication is performed before the addition, so: 3 + 2*5 = 3 + 10 = 13