🔢 Numbers & Math, lesson 3 of 5
Order of operations
How Python decides what to calculate first, plus handy shortcuts like +=.
8 min
2 exercises
2 quizzes
0/4 solved
Getting Python ready… examples can run in a moment.
Python follows the same rules as math class:
( )parentheses first**powers*,/,//,%from left to right+and-from left to right
When in doubt, add parentheses. They make your intention clear to both Python and people.
Precedence in action
Add parentheses to the last line so it calculates (2 * 3) ** 2 instead.
What does this print?
Fix the temperature
To convert Fahrenheit to Celsius: subtract 32, then
multiply by 5 and divide by 9. The formula below gives
the wrong answer. Fix it so celsius is 100.0
for 212 °F.
Updating a variable with its own value is so common that Python has shortcuts called augmented assignment:
| Shortcut | Means |
|---|---|
x += 3 |
x = x + 3 |
x -= 3 |
x = x - 3 |
x *= 3 |
x = x * 3 |
x /= 3 |
x = x / 3 |
Shortcuts
Try points //= 4 and points **= 2 too.
What does this print?
Savings jar
Update savings using augmented assignment:
- add
20with+= - spend
5with-= - triple it with
*=
It should end at 105.