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
| Word | What it means | Example |
|---|---|---|
| Order of operations | The rules for which part of a calculation is worked out first. | |
| Bracket | A ( ) pair. What is inside is worked out first. | (2 + 3) * 4 |
| Efficient | Does the job with little time and little memory. | |
| Execution time | How long a program takes to run. | |
| Memory | The space a program needs to hold its data. | |
| Data structure | A way to store a group of values. | a list, a dictionary |
| List | A group of values kept in order. | [5, 8, 2] |
| Dictionary | A 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 questionsThe 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
| Order | What | Python sign |
|---|---|---|
| 1st | Brackets | ( ) |
| 2nd | Powers | ** (2 ** 3 means 2 x 2 x 2, which is 8) |
| 3rd | Multiply and divide | * (times) and / (divide) |
| 4th | Add and subtract | + and - |
The cells students fill in are left blank in this preview.
Worked example: the average of three marks
| Calculation | Steps | Answer |
|---|---|---|
| 60 + 70 + 80 / 3 | 80 / 3 = 26.67, then 60 + 70 + 26.67 | 156.67: wrong |
| (60 + 70 + 80) / 3 | 60 + 70 + 80 = 210, then 210 / 3 | 70: right |
| 20 * 9 / 5 + 32 | 20 * 9 = 180, then 180 / 5 = 36, then 36 + 32 | 68 |
The cells students fill in are left blank in this preview.
Try it: the order matters
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 questionsOrder 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
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
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?
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 job | A good choice | Why |
|---|---|---|
| Look up a price by the item name | Dictionary | It goes straight to the value: less time |
| Keep scores in the order they were played | List | A list keeps the order |
| Add up 10 million numbers | Do not keep them all | A running total (a number you keep adding to) needs one number: less memory |
| Read a huge file | One line at a time | The 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
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
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