Exercise 0.1: Order of operations: ten expressions to evaluate
Give the value Python computes for each expression. A result that print shows with a decimal point, such as 18.0, is a float: type its value in the field, 18.
Method: brackets first; then **, grouped from right to left and applied before a minus sign written in front; then *, /, // and %, from left to right; then + and -, from left to right. The operator / always gives a float. Here // (integer division) and % (remainder) are used on positive whole numbers only.
- a) 6 + 4 * 3
- b) (6 + 4) * 3
- c) 20 - 8 / 4
- d) 2 ** 2 ** 3
- e) -5 ** 2
- f) (-5) ** 2
- g) 9 / 4
- h) 23 // 5
- i) 23 % 5
- j) 10 - 2 * 3 ** 2 / 6
Show the solution
Answers
- a) 18
- b) 30
- c) 18.0, a float
- d) 256
- e) -25
- f) 25
- g) 2.25
- h) 4
- i) 3
- j) 7.0, a float
The same reading on every line: find the operator that runs first, compute it, rewrite the shorter expression, and start again.
* before +: 4 * 3 = 12, then 6 + 12 = 18, an int.
The brackets first: 6 + 4 = 10, then 10 * 3 = 30.
/ before -: 8 / 4 = 2.0, a float, then 20 - 2.0 = 18.0.
One float in the expression makes the result a float: the value is 18, print shows 18.0.
** is grouped from right to left: 2 ** 2 ** 3 is 2 ** (2 ** 3) = 2 ** 8 = 256.
Pitfall: (2 ** 2) ** 3 = 4 ** 3 = 64, the left-to-right reading.
** runs before the minus sign written in front: -5 ** 2 is -(5 ** 2) = -25.
Pitfall: 25, which is the value of (-5) ** 2.
The brackets make -5 the base: (-5) ** 2 = (-5) × (-5) = 25.
9 / 4 = 2.25: / is true division, even between two int.
In Java, 9 / 4 between two int gives 2, the decimals dropped; Python writes that operation 9 // 4.
23 // 5 counts the whole 5s in 23: 5 × 4 = 20 is at most 23, and 5 × 5 = 25 is more, so 4.
23 % 5 is what is left over: 23 - 20 = 3.
Check: 5 × 4 + 3 = 23.
** first: 3 ** 2 = 9. Then * and / from left to right: 2 * 9 = 18, then 18 / 6 = 3.0. Then 10 - 3.0 = 7.0.