What does Python calculate first?
Python follows the same rules as maths class (sometimes called BODMAS or PEMDAS):
- 1. Brackets
( ) - 2. Powers
** - 3. Multiply and divide
* / // % - 4. Add and subtract
+ -
print(2 + 3 * 4)
print((2 + 3) * 4)Output
14 20
In the first line, 3 * 4 happens first. In the second line the brackets make 2 + 3 happen first.
Tip: When in doubt, add brackets. They make your intention clear to Python and to anyone reading your code.
A real example: the average
a = 70
b = 80
c = 90
wrong = a + b + c / 3
right = (a + b + c) / 3
print("Wrong:", wrong)
print("Right:", right)Output
Wrong: 180.0 Right: 80.0
Shortcut operators
Changing a variable based on its old value is so common that Python has shortcuts:
| Shortcut | Same as |
|---|---|
x += 5 | x = x + 5 |
x -= 5 | x = x - 5 |
x *= 5 | x = x * 5 |
x /= 5 | x = x / 5 |
lives = 3
lives -= 1
print("Lives left:", lives)
points = 100
points += 50
print("Points:", points)Output
Lives left: 2 Points: 150