Skip to content

Informatics Practices · Ch 3 — Brief Overview of Python

Precedence of Operators

3.7.1

Precedence of Operators

When an expression contains more than one operator, Python must decide which operation to perform first — and the answer changes the result. That decision is governed by precedence: an order, or hierarchy, among the operators. The rule is simple to state: a higher-precedence operator is evaluated before a lower-precedence operator.

The most familiar instance of this hierarchy is that * and / have higher precedence than + and -. So in an expression mixing multiplication with addition, the multiplication happens first, regardless of which is written first on the line.

Two supplementary rules complete the picture:

  • Parentheses override precedence. The expression within () is evaluated first, whatever the operators inside it are. Parentheses are your tool for forcing an evaluation order different from the default hierarchy.
  • Equal precedence goes left to right. When two operators have the same precedence, the expression is evaluated from left to right.

Worked example: default precedence

How will Python evaluate the following expression?

20 + 30 * 40

Since the precedence of * is higher than that of +, the multiplication is performed first:

= 20 + 1200    # Step 1: 30 * 40 evaluated first
= 1220         # Step 2

Reading left to right and adding first would give a very different (wrong) answer — precedence, not position on the line, decides the order.

Worked example: parentheses forcing the order

How will Python evaluate this expression?

(20 + 30) * 40

The parentheses force the addition to happen before the multiplication — in effect, + has been given higher precedence than * for this expression:

= (20 + 30) * 40   # Step 1: the bracketed part goes first
= 50 * 40          # Step 2
= 2000             # Step 3

Same numbers, same operators as before — but 1220 became 2000, purely because parentheses changed the order of evaluation.

Worked example: a longer expression

How will the following expression be evaluated?

15.0 / 4.0 + (8 + 3.0)

Step by step:

= 15.0 / 4.0 + (8.0 + 3.0)   # Step 1: the parenthesised sum is taken up first
= 15.0 / 4.0 + 11.0          # Step 2
= 3.75 + 11.0                # Step 3: division precedes addition
= 14.75                      # Step 4

The bracketed part is settled first, then the division (higher precedence), and the addition last. …