Exit
  1. Learn
  2. Check
  3. Solve
  4. Reflect

Multiply before you add

At a shop you buy 3 pencils at 4 rupees each, plus one rubber at 2 rupees. You'd say the bill is 2 plus 3 times 4, which is 14. You would not add 2 and 3 first.

The computer follows the same school rule. Multiplying and dividing happen before adding and subtracting, whatever order you wrote them in. Where the priority is the same, it goes from left to right.

Times and divide: go before plus and minus.
In code
bill = 2 + 3 * 4     # 14, not 20
2 + 3 × 4, one part at a time
2
0
+
1
3
2
×
3
4
4
next

The computer scans the whole line and spots the times sign first. Times goes before plus.

Move 1 of 3

Brackets decide

What if you do want the adding first? Put it in brackets. Whatever is inside brackets happens before anything outside.

This matters when you average numbers. To find the average of three numbers you add them up and then divide by 3. Without brackets, the computer divides only the last number by 3, and then adds. If in doubt, add brackets: they never hurt.

Add up first, then divide? Put the adding in brackets.
In code
wrong = a + b + c // 3
right = (a + b + c) // 3