Order of operations
A calculation is made of operands, the values, and operators, such as + and *. When a calculation has several operators, Python works them out in the order you know from mathematics:
- whatever is in parentheses
- powers,
** - multiplication and division:
*,/,//and% - addition and subtraction:
+and-
Operators on the same level are worked out from left to right. Powers are the exception: 2 ** 3 ** 2 is worked out from the right, as 2 ** 9.
print(2 + 3 * 4)
print((2 + 3) * 4)
print(2 * 3 ** 2)
print(20 - 8 - 2)
print(20 - (8 - 2))
14
20
18
10
14In 2 * 3 ** 2, the power comes first: 3 ** 2 is 9, and 2 * 9 is 18. In 20 - 8 - 2, Python goes from left to right: 20 - 8 is 12, and 12 - 2 is 10. The parentheses in the last line make Python do 8 - 2 first.
A classic mistake
The mean of two numbers is their sum divided by two. Forget the parentheses, and only the second number is divided:
first = 8
second = 6
wrong = first + second / 2
right = (first + second) / 2
print(wrong)
print(right)
11.0
7.0Python gave no error: first + second / 2 is a perfectly good calculation, just not the one that was meant. Its result is 8 + 3.0, which is 11.0. Python always does what the code says, so check that the order of the calculation is what you want.
Parentheses in a longer formula
Here the price of a product drops by 25 percent, and then shipping is added:
price = 80
discount = 25
shipping = 5
total = price * (100 - discount) / 100 + shipping
print(total)
65.0The parentheses make Python work out the share of the price you pay, 75 percent, first. Then * and / go from left to right: 80 * 75 is 6000, and 6000 / 100 is 60.0. The addition comes last. When you aren't sure of the order, add parentheses: they never hurt, and they make the formula easier to read.