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

Preview

Tidy, safe and organised code

This is the first page of the lesson. Read it and have a go at the activities. The rest is in the full lesson.

45 minutes

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 an if. Many levels make code hard to read.if a: if b: if c:
IndentationThe spaces at the start of a line. They show which lines belong together.4 spaces
ConstantA value that never changes, written once with a name 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))

Tidy: the same job

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


def price(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(True, 2, 1))
print(price(False, 3, 2))
print(price(True, 2, 5))

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

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.

Quick check: tidy code

Have a go

Quick 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

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

When the input is wrong: try and except

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

Do not let it. 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?

The lesson goes on

7 more parts of this lesson are in the full curriculum, with the tasks, the final check and the labs. A college account gives your students all of it.