Which comes first? Operator order
🌍 In real life. You buy 2 notebooks at 30 taka each and 1 pen for 10 taka. The bill is 10 + 2 × 30 = 70 taka. Without thinking about it, you multiplied first and added after; adding first, (10 + 2) × 30 = 360, would be a very wrong bill.
Maths has rules about which part goes first, and Python follows the same rules.
The idea in one sentence: Python works out ( ) first, then **, then * / // %, then + -, and operators on the same level go left to right.
Its words:
- precedence: which operator goes first
- brackets
( ): they go first of all, so they let you choose the order
The order, from first to last:
( )brackets**power*,/,//,%+,-
Step by step, for 2 + 3 * 4 - 5:
*is on a higher level than+and-, so3 * 4= 12 first:2 + 12 - 5.+and-are on the same level, so left to right:2 + 12= 14.- Then
14 - 5= 9.
print(2 + 3 * 4)
print((2 + 3) * 4)Brackets let you choose the order yourself. Here they make the + go before the *, and the ** still goes before the *:
When operators are on the same level, Python goes left to right:
print(10 - 4 - 3)
print(20 / 2 * 5)How Python does it. Python reads the whole expression first, then repeatedly picks the operator with the highest level (the leftmost one if there's a tie), works out that small piece, and puts the result back, until one value is left. That's exactly what the tree above shows.
Two surprises, both from **:
**goes right to left:2 ** 3 ** 2is2 ** 9= 512.- A minus sign in front of a number waits for
**:-2 ** 2is-4. Write(-2) ** 2to get 4.
When in doubt, add brackets. They never hurt, and they show clearly what you mean. For example, an average needs brackets around the sum:
average = (7 + 8 + 9) / 3
print(average)print(2 ** 3 ** 2)
print(-2 ** 2)
print((-2) ** 2)Mistakes and edge cases.
- An average without brackets.
7 + 8 + 9 / 3is18.0, because only the 9 is divided. Write(7 + 8 + 9) / 3. - A bracket left open.
print((2 + 3) * 4givesSyntaxError: '(' was never closed. Count your brackets: every(needs a). - Square brackets for maths. Only round brackets group maths.
[2 + 3] * 4makes something else entirely (a list, Chapter 8). - A minus sign and power.
-2 ** 2is-4, not 4.
Quiz
What does this print?
print(1 + 2 * 3)What does this print?
print((1 + 2) * 3)What does this print?
print(2 ** 2 * 3)What does this print?
print(10 - 2 - 3)In
8 - 6 // 2, which part does Python work out first?- 8 - 6
- 6 // 2
This should print the average of 4 and 6, which is 5.0. Which line is wrong?
a = 4 b = 6 print(a + b / 2)
Coding tasks
Add brackets to line 1 so that
resultbecomes 20.Three test scores are given. Make
averagehold their average: add them up, then divide by 3.