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 6.1 (8 of 10): Coding conventions

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

Can you read this?

Here is a line from a real program: x = a * b - c.

What is x? What are a, b and c? Nobody knows. The writer will not remember in six months.

Now read this: final_price = price * quantity - voucher. You understand it at once. The same code is easy to read when it follows good habits.

Key words

WordWhat it meansExample
VoucherA code that takes money off the price.5 pounds off
VariableA name that holds a value.price
FunctionA named block of code that does one job.total_price()
ConstantA value that never changes while the program runs.MAX_SIZE
ConventionA habit that a whole team agrees to follow.
Naming conventionA team rule for how to write names.total_price
camelCaseJoined words, each new word starting with a capital.totalPrice
CommentA note in the code for people to read.# add the tax
DocstringA note in triple quotes that says what a function does.
ModularBuilt from small separate parts, each with one job.
IndentationSpaces at the start of a line that group lines together.
ReadabilityHow easy the code is to read.
MaintainabilityHow easy the code is to change later.
Version controlA tool that keeps every version of your files.

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

Names that say what things are

A good name tells the reader what a value is or what a function does.

Use whole words: average_mark, not am. Use a verb for a function: calculate_total. Use a noun for a value: price.

A team also agrees one style. That is the naming convention.

The same code, before and after tidying

Code: python
# BEFORE: it works, but it is hard to read
def f(a,b):
  x=0
  for i in a:
    x=x+i
  return x-b


# AFTER: the same job, easy to read
def total_price(prices, voucher):
    """Add up the prices and take off the voucher."""
    total = 0
    for price in prices:
        total = total + price
    return total - voucher


print(f([5, 3, 2], 4))
print(total_price([5, 3, 2], 4))

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

Common naming styles

StyleLooks likeOften used for
snake_casetotal_pricePython variables and functions
camelCasetotalPriceJavaScript and Java variables and functions
PascalCaseTotalPriceClasses in most languages
UPPER_CASEMAX_SIZEConstants: values that never change

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

Spot the bad code

Have a go

Spot the bad 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

Comments: say why, not what

A comment is a note for people. The computer ignores it.

Do not repeat the code. # add 1 above count = count + 1 says nothing new. Say why: # the first row is the header, so skip it.

A docstring goes inside a function and says what it does and what it gives back.

Small parts and clear layout

Modular code is made of small functions. Each does one job. You can test each one. You can reuse it.

Good structure helps too. Put imports at the top, then constants, then functions. Use the same indentation everywhere. Python uses four spaces. In Python it is not only style: the indentation is part of the language.

Match the convention

Have a go

Loading…

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

Version control is a convention too

Teams also agree how to use version control. Make small commits. Write a clear message for each one. Never put passwords in the code or the history.

A good message says what changed and why.

Commit messages

Poor messageGood message
fixFix total when the voucher is bigger than the price
changesAdd is_adult check to the sign-up form
stuffMove the discount code into its own function

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

Tidy the code with good names

The starter code works but is hard to read. Rewrite it with good names, a docstring in every function, and four spaces of indentation. Then add format_report, which must use average_mark. The hidden tests check what each function gives back, the names and the docstrings. Press Run Tests.

Code: python
# This code works, but nobody can read it. Tidy it.
# Make four small functions with good names and a docstring in each. The last one uses another:
#   total_price(prices, voucher)  the sum of prices, minus the voucher, never below 0
#   is_adult(age)                 True if age is 18 or more
#   average_mark(marks)           the sum of marks divided by how many, or 0 for an empty list
#   format_report(name, marks)    text like: Aisha: average 70   (round the average to a whole number)
# A docstring is a text in triple quotes on the first line inside the function.

def f(a,b):
  x=0
  for i in a:
    x=x+i
  if x-b<0:return 0
  return x-b
def g(a):
  return a>=18
def h(l):
  if len(l)==0:return 0
  return sum(l)/len(l)

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

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.