Four spellings of one branch
The branch is typed as North, north, NORTH and " North ". To a person they are the same. To a program they are four different values.
A cleaning step turns all four into one. Then every count and every total agrees.
Key words
| Word | What it means |
|---|---|
| Function | a named block of code that takes a value and gives one back |
| Float | a number with a decimal point, such as 12.5 |
| String | text in code, such as "North" |
| Dictionary | a collection of values, each found by a name called a key |
| Exception | an error that stops code unless you handle it |
| Cleanse | to correct or remove bad data so what is left can be trusted |
| Convention | an agreed way of writing something |
The cells students fill in are left blank in this preview.
By the end of this lesson
Note
I can write small functions that clean text, turn text into numbers safely, and list the problems in a record.
Starter
Have a go
Starter
3 questionsYour answers are marked here and are not kept. A college account keeps every student’s marks.
This is practice
Important
The real task comes from the exam board. This lesson uses an invented organisation and its own made-up data. Your teacher tells you how the real tasks are set and what you may bring.
Run it: tidy a string
text = " sam OKOYE "
print(repr(text))
words = text.strip().split()
result = []
for word in words:
result.append(word.capitalize())
print(" ".join(result))Worked example: the tools for tidy text
| Tool | What it does | Input | Output |
|---|---|---|---|
| strip() | Takes spaces off both ends | " North " | "North" |
| capitalize() | Capital first letter, the rest small | "SOUTH" | "South" |
| split() | Cuts text into a list of words | "sam okoye" | ["sam", "okoye"] |
| replace(a, b) | Swaps every a for b | "£12.50" | With "£" replaced by "": "12.50" |
| float() | Turns text into a number | "12.50" | 12.5 |
The cells students fill in are left blank in this preview.
Turning text into a number safely
float("twenty") stops the code with an exception, a ValueError. You can catch it with try and except. Then the code carries on and gives back None, which means "no number".
Never let one bad row stop the whole file.
Run it: catch the exception
def to_amount(text):
text = text.strip().replace("£", "")
try:
return float(text)
except ValueError:
return None
for item in ["£12.50", " 40 ", "twenty"]:
print(repr(item), "->", to_amount(item))