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

Free lesson

OS 4.3 (5 of 12): Data types, validation and structures

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.

50 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

What if they type "banana"?

Your form asks for age. One user types 16. Another types -5. Another types banana. Another leaves it empty.

A good program does not crash. It does not accept wrong data. It tells the user what to fix.

You plan this at the design stage.

Key words

WordWhat it means
Data validationChecking that data is sensible before the program uses it.
Presence checkChecks that something was entered.
Range checkChecks that a number is between a lowest and a highest value.
Length checkChecks that text is not too short or too long.
Type checkChecks that the data is the right kind.
Format checkChecks that the data has the right pattern.
Data structureA way to organise many values, so the program can use them well.
StackA structure where the last item in is the first out.
QueueA structure where the first item in is the first out.

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

Five validation checks

CheckQuestion it asksPassesFails
PresenceIs it empty?Sam(nothing)
RangeIs it between 0 and 120?16121, 200
LengthIs it 3 to 12 characters?sam2026ab
TypeIs it a whole number?16banana
FormatDoes it look like an email address?[email protected]sam.mail.com

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

Quick check: which check?

Have a go

Quick check: which check?

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

A validator that refuses bad marks

Code: python
def check_mark(text):
    if text == "":
        return "Please type a mark"
    if not text.isdigit():
        return "A mark is a whole number"
    mark = int(text)
    if mark > 100:
        return "The highest mark is 100"
    return "ok"


for typed in ["", "abc", "150", "72"]:
    print(repr(typed), "->", check_mark(typed))

# Try a mark of "-3". What does the program say? Why?
# Add "-3" to the list and run it again.

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

Validation is not verification

Important

Many people think validation proves data is true. It only checks that data is sensible. A date of birth in the future fails, but a wrong age that looks sensible passes. Verification means checking that data is correct, for example by asking the user to type it twice.

More key words: types and structures

WordWhat it meansExample
Data typeThe kind of value a field holds.
IntegerA whole number with no decimal point.16
FloatA number with a decimal point.2.50
StringText."Sam"
BooleanTrue or False.
ArrayA list of values in order, found by their position.
TupleA fixed group of values that cannot change.
DictionaryPairs of a name (key) and a value, so you can look a value up by its name.

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

Choose a data type for each field

FieldData typeWhy
AgeIntegerA whole number
Price in poundsFloat, or integer penceHas a decimal point. Pence avoid rounding errors
Phone numberStringYou never add phone numbers. It can start with 0
Is a memberBooleanOnly yes or no
NameStringText

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

Choose the type of each field

Have a go

Choose the type of each field

6 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

Choose a data structure

A data structure holds many values. Pick the one that fits how you use the data.

Use a list for items in order. Use a dictionary to find a value by its name. Use a stack for undo: the last action is undone first. Use a queue for waiting: the first person is served first.

Data structures at a glance

StructureHow it worksExample
List or arrayItems in order, found by positionThe scores in a game
DictionaryPairs of a key and a valueMenu: item and price
TupleA fixed group that cannot changeA point (3, 5) on a map
StackLast in, first outUndo history in an editor
QueueFirst in, first outPeople waiting for a table

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

A stack and a queue in Python

Code: python
history = ["type a", "type b", "delete"]
print("Undo:", history.pop())      # the last one out
print(history)

queue = ["Aisha", "Ben", "Sam"]
print("Serve:", queue.pop(0))      # the first one out
print(queue)

menu = {"pizza": 8, "chips": 3}
print(menu["pizza"])

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

Validate data and organise it

Finish five functions. Three check data: age, user name and a menu lookup. Two use data structures: an undo stack and a queue. Read the comment in each one. Press Run Tests.

Code: python
def check_age(text):
    # text is what the user typed. Give back one of these:
    #   "Age is required"            if text is empty
    #   "Please enter a number"      if text is not made of digits
    #   "Age must be 0 to 120"       if the number is outside 0 to 120
    #   "ok"                         otherwise
    return None


def check_username(name):
    # True if the name is 3 to 12 characters and only letters or digits. Else False.
    return None


def price_of(menu, item):
    # menu is a dictionary of item to price. Give back the price, or None if the item is not on the menu.
    return None


def undo(history):
    # history is a list of actions. It is a stack: the last action added is the first one removed.
    # Remove the last action from the list and give it back. If the list is empty, give back None.
    return "nothing"


def serve_next(queue):
    # queue is a list. It is a queue: the first person added is the first one served.
    # Remove the first person and give them back. If the list is empty, give back None.
    return "nobody"

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.