Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

2.9 (1 of 3): Order, speed and memory

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

45 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

Tea in the wrong order

Making tea has an order. Boil the water. Put the tea bag in the cup. Pour the water. If you pour before the water boils, you get a cup of cold, weak tea.

Programs are the same. Order decides if the answer is right. It also decides if the program is quick.

Key words

WordWhat it meansExample
Order of operationsThe rules for which part of a calculation is worked out first.
BracketA ( ) pair. What is inside is worked out first.(2 + 3) * 4
EfficientDoes the job with little time and little memory.
Execution timeHow long a program takes to run.
MemoryThe space a program needs to hold its data.
Data structureA way to store a group of values.a list, a dictionary
ListA group of values kept in order.[5, 8, 2]
DictionaryA group of pairs. You find a value by its key.{"tea": 1.2}

The cells students fill in are left blank in this preview.

Put the actions in a logical order

Some steps need others to finish first. You cannot add up a bill before you have the prices. You cannot read a file before you open it.

Work backwards. Ask: what does this step need? Put that step earlier.

Quick check: the logical order

Have a go

Quick check: the logical order

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

The order inside a calculation

A calculation has an order too. Python follows the same rules as your maths lessons. Brackets come first. Then powers. Then multiply and divide. Then add and subtract.

When two operations are at the same level, Python goes from left to right. A bracket is the easy way to be sure.

The order of operations

OrderWhatPython sign
1stBrackets( )
2ndPowers** (2 ** 3 means 2 x 2 x 2, which is 8)
3rdMultiply and divide* (times) and / (divide)
4thAdd and subtract+ and -

The cells students fill in are left blank in this preview.

Worked example: the average of three marks

CalculationStepsAnswer
60 + 70 + 80 / 380 / 3 = 26.67, then 60 + 70 + 26.67156.67: wrong
(60 + 70 + 80) / 360 + 70 + 80 = 210, then 210 / 370: right
20 * 9 / 5 + 3220 * 9 = 180, then 180 / 5 = 36, then 36 + 3268

The cells students fill in are left blank in this preview.

Try it: the order matters

Code: python
print(60 + 70 + 80 / 3)
print((60 + 70 + 80) / 3)
print(2 + 3 * 4)
print((2 + 3) * 4)
print(2 ** 3 + 1)

# Predict each answer before you run it.

Make a free account to save your work and track your progress.

Quick check: what is the answer?

Have a go

Quick check: what is the answer?

4 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Order for speed and safety

Order can prevent errors. Check that the number of people is not 0 before you divide by it.

Order can save time too. Do the quick check first. Stop a search as soon as you find the answer. Remove data you do not need before you sort it.

Try it: count the steps

Code: python
def steps_to_find(scores):
    steps = 0
    for score in scores:
        steps = steps + 1
        if score == 100:
            return steps
    return steps

print(steps_to_find([100, 5, 7, 9, 3]))
print(steps_to_find([5, 7, 9, 3, 100]))

# Stopping early is quick when the answer is near the start.

Make a free account to save your work and track your progress.

Extra: Try it: and stops at the first False

Code: python
people = 0
bill = 30

if people > 0 and bill / people < 10:
    print("Cheap night out")
else:
    print("Not cheap, or nobody came")

# With and, Python stops at the first False.
# people > 0 is False, so Python never divides by 0.
# Swap the two checks and run it. What happens?

Make a free account to save your work and track your progress.

The right data structure saves time

A data structure holds your data. The choice changes the time and the memory.

To find a price by name, a list of pairs makes you look at one pair after another. A dictionary goes straight to the answer.

Try it: list or dictionary?

Code: python
pairs = [["tea", 1.2], ["coffee", 2.5], ["cake", 3.0], ["juice", 1.8]]
prices = {"tea": 1.2, "coffee": 2.5, "cake": 3.0, "juice": 1.8}

steps = 0
for pair in pairs:
    steps = steps + 1
    if pair[0] == "juice":
        print("List: price", pair[1], "after", steps, "steps")

print("Dictionary: price", prices["juice"], "in 1 step")

Make a free account to save your work and track your progress.

Which data structure?

The jobA good choiceWhy
Look up a price by the item nameDictionaryIt goes straight to the value: less time
Keep scores in the order they were playedListA list keeps the order
Add up 10 million numbersDo not keep them allA running total (a number you keep adding to) needs one number: less memory
Read a huge fileOne line at a timeThe whole file never sits in memory

The cells students fill in are left blank in this preview.

Match the problem to the fix

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Watch: order, speed and memory

Press Play on the short film below. It runs the programs from this lesson, one at a time. Watch how the order changes the answer, and how the order and the data structure change the number of steps.

Film: order, speed and memory

Order, speed and memory

Every scene, as text

  1. Myth (false): the order of operations is only for maths class. Python follows the same rules: in print(60 + 70 + 80 / 3) it works out 80 / 3 first, then adds 60 and 70, so it prints 156.66666666666666. That is not the average of 60, 70 and 80.
  2. The cure is a bracket: what is inside is worked out first. In print((60 + 70 + 80) / 3), 60 + 70 + 80 is 210, then 210 / 3 prints 70.0, the average. When two operations are at the same level, Python goes from left to right: in print(20 * 9 / 5 + 32), 20 * 9 is 180, 180 / 5 is 36, then 36 + 32 prints 68.0.
  3. Order can prevent errors. people is set to 0 and bill to 30. The if line asks two things joined by and: people > 0 and bill / people < 10. With the word and, Python stops at the first False. people > 0 is False, so Python never works out bill / people (struck through), never divides by 0, and the else part prints Not cheap, or nobody came.
  4. Order can save time too: stop a search as soon as you find the answer. steps_to_find adds 1 to steps for each score, and return stops it at the first 100. The two calls do the same job: with 100 first it prints 1; with 100 last it looks at all five scores and prints 5.
  5. The right data structure saves time. Both programs find the price of juice. With a list of pairs, the loop looks at one pair after another, adding 1 to steps each time; juice is the fourth pair, so it prints List: price 1.8 after 4 steps. A dictionary is a group of pairs, and you find a value by its key: prices["juice"] goes straight to the price, and it prints Dictionary: price 1.8 in 1 step. For 4 items the difference is small; imagine 4 million.
  6. Less memory: to add up 10 million numbers, do not keep them all. A running total needs one number: total starts at 0 and each number is added to it. range gives the numbers one at a time, so none of them is kept, and it prints 50000005000000. Reading a huge file one line at a time saves memory the same way: the whole file never sits in memory.

Your turn: fix the order

Two functions have an order bug: average_of_three and to_fahrenheit. Fix them with brackets or by changing the calculation. Then finish three more. safe_share shares a bill and must not divide by 0. price_of looks an item up in the dictionary and gives back 0.0 if it is missing. first_full_marks gives back the position of the first score of 100, and stops as soon as it finds it. Press Run Tests to check.

Code: python
PRICES = {"tea": 1.2, "coffee": 2.5, "cake": 3.0}


def average_of_three(a, b, c):
    # Give back the average of the three marks. This has a bug. Fix it.
    return a + b + c / 3


def to_fahrenheit(celsius):
    # Celsius times 9, divided by 5, plus 32. This has a bug. Fix it.
    return celsius * 9 / (5 + 32)


def safe_share(total, people):
    # Share a bill between people. Give back total divided by people.
    # If people is 0, give back 0 and do not divide.
    return None


def price_of(item):
    # Look the item up in the PRICES dictionary.
    # If it is not there, give back 0.0.
    return None


def first_full_marks(scores):
    # Give back the position (starting at 0) of the first score that is 100.
    # Stop as soon as you find it. If there is none, give back -1.
    return None

Make a free account to save your work, or press Start lab to work through the whole lesson.

Key words crossword

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.