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

Free lesson

ESP task 4a (2 of 5): Tidy, safe and organised code

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

Fix it at midnight

Imagine the booking program breaks on Saturday night. You must fix it. Which would you rather open?

One: 80 lines with an if inside an if inside an if, and the same code pasted five times.

Two: small functions (named pieces of code that do one job) with clear names, notes and no repeats.

Marks go to code that a stranger can read, trust and change.

Key words

WordWhat it meansExample
Nested ifAn if inside another if.if a: if b: if c:
IndentationThe spaces at the start of a line. They show which lines belong together.4 spaces
ConstantA named value that never changes, written in CAPITAL LETTERS.LAST_HOUR = 20
Local variableA name that works only inside one function.rate inside price_for
Global variableA name made outside every function. Any function can change it.bookings = []
ExceptionAn error that happens while the program runs.int("abc") fails
Defensive programmingWriting code that expects wrong input and handles it.check the hour first
ModuleA file of code that other code can use with import.math
InterfaceWhat a module shows to others: the names, the inputs and the outputs.price_for(is_member, hours)

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

Messy: the price check

Code: python
def price(m, h, c):
    if m == True:
        if h > 0:
            if c == 1 or c == 2:
                return h * 4
            else:
                return -1
        else:
            return -1
    else:
        if h > 0:
            if c == 1 or c == 2:
                return h * 6
            else:
                return -1
        else:
            return -1


print(price(True, 2, 1))
print(price(False, 3, 2))
print(price(True, 2, 5))

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

Tidy: the same job

Code: python
MEMBER_RATE = 4
VISITOR_RATE = 6
COURTS = [1, 2]


def price_for(is_member, hours, court):
    # Refuse a bad request first, then do the real work.
    if hours <= 0 or court not in COURTS:
        return None
    rate = VISITOR_RATE
    if is_member:
        rate = MEMBER_RATE
    return rate * hours


print(price_for(True, 2, 1))
print(price_for(False, 3, 2))
print(price_for(True, 2, 5))

# The prices are written once. Change MEMBER_RATE to 5 and run it again.

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

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.

A checklist for tidy code

CheckWhy it helps
Each function does one jobYou can test and fix it alone
Indentation is the same everywherePython needs it, and readers see the shape
Comments say why, not whatThe reader learns the reason
Values that never change are constantsYou change a price in one place
Variables are local when they can beA bug cannot hide in another part of the program
One naming and layout styleThe whole program reads the same

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

Check: tidy code

Have a go

Check: tidy code

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

try and except handle wrong input

A person types "abc" where a number belongs. int("abc") causes an error called an exception. The program stops.

Stop that happening. Put the line that may fail in try. Put the plan for the failure in except.

This is defensive programming: expect wrong input and have a plan.

Try it: catch an exception

Code: python
def to_number(text):
    try:
        return int(text)
    except ValueError:
        return None


print(to_number("12"))
print(to_number("abc"))
print(to_number(""))

# Remove try and except. Run it again. What happens?

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

Handle data securely

Tip

Defensive code also protects people. Check typed text before you use it. Never print a full phone number or a password. Do not write secrets in the code file. The Make code safer lesson shows how.

Stage 4a: constants and exceptions

Make this code tidy and safe. Set the two rate constants to 4 and 6. rate_for uses them. to_hour uses try and except and gives back an hour from 9 to 20, or None. average_hour uses to_hour, skips the bad texts and gives the average of the rest, rounded to 1 decimal place. Press Run Tests to check your work.

Code: python
OPEN_HOUR = 9
LAST_HOUR = 20
MEMBER_RATE = 0     # set this to the member price
VISITOR_RATE = 0    # set this to the visitor price


def rate_for(is_member):
    # Give back the rate for one hour. Use the two constants above.
    return None


def to_hour(text):
    # text is what a person typed. Use try and except.
    # Give back the hour as an integer if it is a whole number from OPEN_HOUR to LAST_HOUR.
    # Give back None for anything else, such as "abc", "" or "10.5".
    return None


def average_hour(texts):
    # texts is a list of typed hours. Use to_hour for each one.
    # Skip the bad ones. Give back the average of the good ones, rounded to 1 decimal place.
    # Give back None if there are no good ones.
    return None

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

A module is code you import

A module is a file of code you use with import. Some are written for you: math, random, datetime. Some you write: prices.py with your own price_for.

You do not need to know how a module works inside. You need its interface: the names, what goes in and what comes out.

Try it: a module that is already written

Code: python
import math

minutes = 70
hours_billed = math.ceil(minutes / 60)
print(hours_billed)

# math.ceil rounds up. 70 minutes is 1.17 hours, so 2 hours are billed.
# Try 60 minutes, then 61 minutes.

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

The interface of your own module

FunctionWhat goes inWhat comes out
price_foris_member (True or False), hours (a whole number)The price in pounds
to_hourtext typed by a personAn hour from 9 to 20, or None
is_freethe bookings, a court, an hourTrue or False

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

Key words crossword

Have a go

Loading…

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

Final check

Have a go

Final check

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.