Order of operations

Numbers & Math, lesson 3 of 5

🔢 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:

  1. ( ) parentheses first
  2. ** powers
  3. *, /, //, % from left to right
  4. + and - from left to right

When in doubt, add parentheses. They make your intention clear to both Python and people.

Walkthrough

Working out 1 + 2 * 3 ** 2

1+2*3**2
Step 1 of 4

Python doesn't just go left to right. Powers come first: 3 ** 2 is 9.

calculated next
the result
Example

Precedence in action

Add parentheses to the last line so it calculates (2 * 3) ** 2 instead.

Quiz

What does this print?

Exercise

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
Example

Shortcuts

Try points //= 4 and points **= 2 too.

Quiz

What does this print?

Exercise

Savings jar

Update savings using augmented assignment:

  1. add 20 with +=
  2. spend 5 with -=
  3. triple it with *=

It should end at 105.