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
| Word | What it means | Example |
|---|---|---|
| Nested if | An if inside another if. | if a: if b: if c: |
| Indentation | The spaces at the start of a line. They show which lines belong together. | 4 spaces |
| Constant | A named value that never changes, written in CAPITAL LETTERS. | LAST_HOUR = 20 |
| Local variable | A name that works only inside one function. | rate inside price_for |
| Global variable | A name made outside every function. Any function can change it. | bookings = [] |
| Exception | An error that happens while the program runs. | int("abc") fails |
| Defensive programming | Writing code that expects wrong input and handles it. | check the hour first |
| Module | A file of code that other code can use with import. | math |
| Interface | What 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
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
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
| Check | Why it helps |
|---|---|
| Each function does one job | You can test and fix it alone |
| Indentation is the same everywhere | Python needs it, and readers see the shape |
| Comments say why, not what | The reader learns the reason |
| Values that never change are constants | You change a price in one place |
| Variables are local when they can be | A bug cannot hide in another part of the program |
| One naming and layout style | The 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 questionstry 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
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.
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
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
| Function | What goes in | What comes out |
|---|---|---|
| price_for | is_member (True or False), hours (a whole number) | The price in pounds |
| to_hour | text typed by a person | An hour from 9 to 20, or None |
| is_free | the bookings, a court, an hour | True 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