KTU S1

Python Operators and Their Precedence

By the end you should be able to: Evaluate Python expressions by applying operator precedence and associativity correctly, and predict the result of mixed-operator expressions without running them.

When an expression contains more than one operator, Python needs a rule for which to apply first. That rule is precedence. When two operators have the same precedence, associativity decides the order.

This is examinable in Part A almost every year, and it's a common source of lost marks in the lab exam — because a wrong precedence assumption produces a program that runs perfectly and gives the wrong number.

The table, highest precedence first

LevelOperatorsAssociativity
1() parentheses—
2** exponentright to left
3+x, -x, ~x unaryright to left
4*, /, //, %left to right
5+, - binaryleft to right
6<<, >>left to right
7&left to right
8^left to right
9|left to right
10==, !=, <, >, <=, >=left to right
11notright to left
12andleft to right
13orleft to right

You don't need to memorise all thirteen levels. You need the top five cold, plus the fact that comparisons bind tighter than and, which binds tighter than or.

The three that catch people out

1. ** associates right to left.

2 ** 3 ** 2     # 512, not 64

Python computes 3 ** 2 = 9 first, then 2 ** 9 = 512. Every other arithmetic operator goes left to right; this one doesn't.

2. Unary minus binds looser than **.

-2 ** 2         # -4, not 4
(-2) ** 2       # 4

The exponent applies to 2, and the minus is applied to the result.

3. / and // are different operators.

7 / 2           # 3.5   true division, always float
7 // 2          # 3     floor division
-7 // 2         # -4    floors toward negative infinity, not toward zero

That last one surprises almost everyone. // rounds down, so -3.5 becomes -4, not -3.

The % operator with negatives

7 % 3           # 1
-7 % 3          # 2    (not -1)

Python's result always carries the sign of the divisor. The identity that holds is a == (a // b) * b + (a % b).

Practical advice

Use parentheses whenever an expression has more than two operators. It costs nothing at runtime, and the marks you save in the lab exam are real. Knowing the precedence table is for reading code — including exam questions. Writing parenthesised code is for everyone who reads yours later.