Skip to main content

Section 2.12 Order of Operations

When more than one operator appears in an expression, the order of evaluation depends on the rules of precedence. Python follows the same precedence rules for its mathematical operators that mathematics does.
  1. Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 * (3 - 1) is 4, and (1 + 1) ** (5 - 2) is 8. You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60, even though it doesn’t change the result.
  2. Exponentiation has the next highest precedence, so 2 ** 2 + 1 is 5 and not 8, and 3 * 1 ** 3 is 3 and not 27. Can you explain why?
  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 rather than 4, and 5 - 2 * 2 is 1, not 6.
  4. Operators with the same precedence (except for **) are evaluated from left-to-right. In algebra we say they are left-associative. So in the expression 6 - 3 + 2, the subtraction happens first, yielding 3. We then add 2 to get the result 5. If the operations had been evaluated from right to left, the result would have been 6 - (3 + 2), which is 1.

Note 2.12.1.

An exception to the left-to-right left-associative rule is the exponentiation operator **. A useful hint is to always use parentheses to force exactly the order you want when exponentiation is involved:
See the appendix 1 for all the operators introduced in this book. You will also see many upcoming non-mathematical Python operators.

Checkpoint 2.12.2.

    What is the value of the following expression:
    16 - 2 * 5 // 3 + 1
    
  • 14
  • Using parentheses, the expression is evaluated as (2*5) first, then (10 // 3), then (16-3), and then (13+1).
  • 24
  • Remember that * has precedence over -.
  • 3
  • Remember that // has precedence over -.
  • 13.667
  • Remember that // does integer division.

Checkpoint 2.12.3.

    What is the value of the following expression:
    2 ** 2 ** 3 * 3
    
  • 768
  • Exponentiation has precedence over multiplication, but its precedence goes from right to left! So 2 ** 3 is 8, 2 ** 8 is 256 and 256 * 3 is 768.
  • 128
  • Exponentiation (**) is processed right to left, so take 2 ** 3 first.
  • 12
  • There are two exponentiations.
  • 256
  • Remember to multiply by 3.
Here are animations for the above expressions:

Checkpoint 2.12.4.

16 - 2 * 5 // 3 + 1

Checkpoint 2.12.5.

2 ** 2 ** 3 * 3