The scoreboard shows nothing
You build a scoreboard. You sort the scores and print the result. The screen says None.
No error message. Just None. Where is the mistake? Many bugs with lists and dictionaries look like this. In this lesson you learn to spot them.
Key words
| Word | What it means | Example |
|---|---|---|
| Debug | Find and fix mistakes. | change len(items) to len(items) - 1 |
| IndexError | You asked for a list position that does not exist. | items[5] in a list of 3 |
| KeyError | You asked for a dictionary key that does not exist. | menu["pie"] with no pie |
| Off by one | A mistake where an index is one too big or one too small. | items[len(items)] |
| List | One name that holds many values in order. | [1, 2, 3] |
| Dictionary | A data structure of keys and values. | {"tea": 2} |
| Index | The position number in a list. It starts at 0. | 0 |
| Function | A named piece of code that does one job. | max(scores) |
The cells students fill in are left blank in this preview.
Try it: the sort surprise
scores = [30, 10, 20]
result = scores.sort()
print(result)
print(scores)
# sort() changes the list itself. It gives back None.
# Fix: sort, then print the list.
The five mistakes you will meet
| Mistake | What you see | The fix |
|---|---|---|
| Index too big (off by one) | IndexError: list index out of range | The last index is len(items) - 1 |
| Missing key | KeyError: the key | Check with in first |
| Using the result of sort() | None is printed | Call sort(), then use the list |
| Adding in the wrong place | The new item is at the end, not the start | Use insert(0, item) for the start |
| Mixing up index and value | The wrong item or an error | Say aloud: position or value? |
The cells students fill in are left blank in this preview.
Spot the mistake
Have a go
Spot the mistake
3 questionsYour answers are marked here and are not kept. A college account keeps every student’s marks.
Try it: insert, append and pop
a = [1, 2]
a.append(3)
print(a)
a.insert(0, 9)
print(a)
last = a.pop()
print(last)
print(a)
# append adds at the end.
# insert adds at an index.
# pop takes the last one out.
Try it: fix the bug
items = ["tea", "cake", "pie"]
last = items[len(items)]
print(last)
# This stops with an IndexError.
# Change the index so it prints pie.
Extra: Try it: two names, one list
a = [1, 2]
b = a
b.append(3)
print(a)
c = a.copy()
c.append(4)
print(a)
print(c)
# b = a gives the same list a second name.
# So a changes too.
# copy() makes a new list. a does not change.
Useful tools for building
Python has functions that save work. max() gives the biggest value. min() gives the smallest. len() counts. count() counts one value.
To find an average, add the values up. Then divide by how many there are.