2.9. 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.0 * (3.0 - 1.0) is 4.0, and (1.0 + 1.0) ** (5.0 - 2.0) is 8.0.

  2. Exponentiation has the next highest precedence, so 2.0 ** 1.0 + 1.0 is 3 and not 4, and 3.0 * 1.0 ** 3.0 is 3.0 and not 27.0. Can you explain why?

  3. Multiplication and both division have the same precedence, which is higher than addition and subtraction, which also have the same precedence. So 2.0 * 3.0 - 1.0 yields 5.0 rather than 4.0, and 5.0 - 2.0 * 2.0 is 1.0, not 6.0.

  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.0 - 3.0 + 2.0, the subtraction happens first, yielding 3.0. We then add 2.0 to get the result 5.0. If the operations had been evaluated from right to left, the result would have been 6.0 - (3.0 + 2.0), which is 1.0.

Note

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 Operator precedence table for all the operators introduced in this book. You will also see many upcoming non-mathematical Python operators.

Check your understanding

    data-9-1: What is the value of the following expression:

    16.0 - 2.0 * 5.0 / 3.0 + 1.0
    
  • 13.667
  • Using parentheses, the expression is evaluated as (2.0 * 5.0) first, then (10.0 / 3.0), then (16.0 - 3.0), and then (13.0 + 1.0).
  • 24.0
  • Remember that * has precedence over -.
  • 3.0
  • Remember that / has precedence over -.

    data-9-2: What is the value of the following expression:

    2.0 ** 2.0 ** 3.0 * 3.0
    
  • 768.0
  • Exponentiation has precedence over multiplication, but its precedence goes from right to left! So 2.0 ** 3.0 is 8.0, 2.0 ** 8.0 is 256.0 and 256.0 * 3.0 is 768.0.
  • 128.0
  • Exponentiation (**) is processed right to left, so take 2.0 ** 3.0 first.
  • 12.0
  • There are two exponentiations.
  • 256.0
  • Remember to multiply by 3.0.

Here are animations for the above expressions:

16.0 - 2.0 * 5.0 / 3.0 + 1.0
2.0 ** 2.0 ** 3.0 * 3.0
You have attempted of activities on this page
2.8. Input"> 2.10. Reassignment">Next Section - 2.10. Reassignment