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

Free lesson

2.9 (2 of 3): Names and code style

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.

40 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

Which program would you fix?

Two programmers write the same program. One uses the names x, y and z. The other uses tickets, fare and total.

Both programs have a bug and you must fix one today. Which one would you rather fix? Code is read many more times than it is written. Style is how you make it easy to read.

Key words

WordWhat it meansExample
Naming conventionA set of rules for how names are written.
Meaningful nameA name that says what the value is or what the code does.total_price
snake_caseSmall (lower-case) letters, with an underscore _ between words.total_price
camelCaseNo spaces. Each new word starts with a capital letter.totalPrice
White spaceSpaces, blank lines and indents that make code easy to see.
Line lengthHow many characters are on one line.
ReadabilityHow easy the code is to read and understand.
VariableA name that holds a value.
FunctionA named piece of code that does a job.

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

Run it: hard to read

Code: python
x=5
y=2.5
z=x*y
d=z-1
print("Pay",d)

# It works. But what is x? What is d?
# Can you tell what this program is for?

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

Run it: easy to read

Code: python
tickets = 5
fare = 2.5
total = tickets * fare
discounted_total = total - 1
print("Pay", discounted_total)

# The same program. Now the names explain what it does.

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

A good name says what a value is

A good name says what a value is. fare is better than f. is_late is better than flag.

Do not make names too long. number_of_tickets_the_customer_wants is too much. A name has no spaces and does not start with a digit. Python sees Total and total as two names.

Two naming conventions

ConventionHow it looksWhere it is used
snake_casetotal_price, first_namePython: the Python style guide asks for it
camelCasetotalPrice, firstNameJavaScript and Java, for variables and functions
Mixed stylestotal_Price, TotalPrice2Nowhere: pick one style and use it every time

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

Match camelCase to snake_case

Have a go

Loading…

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

White space and line length

White space is free. Use it. Put spaces around symbols such as = and +: total = a + b. Leave a blank line between two functions. Indent by 4 spaces.

Keep lines short. The Python style guide says 79 characters at most. A long line forces the reader to scroll sideways. Break it into two lines.

A team picks one style

Tip

Some teams use a longer line, such as 100 characters. The exact number matters less than everybody using the same one.

Tidy it up

Code: python
def f(a,b):
  c=a*b
  return c
n=7
print(f(n,2.5),"is the cost of",n,"tickets at a fare of",2.5,"each, which is a lot")

# Rewrite this code. Use meaningful names, snake_case,
# spaces around signs, 4-space indents and two shorter lines.

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

Watch: names and style

Press Play on the short film below. It runs the two programs from the start of the lesson, shows the two naming styles, and tidies up a function. Watch what changes for Python and what changes for you.

Film: names and code style

Names and code style

Every scene, as text

  1. Myth (false): Python needs good names to run the code. The lesson's program with x, y, z and d, and no spaces round its signs, runs and prints Pay 11.5. It works, but what is x? What is d? Nobody reading it can tell what it is for.
  2. The same program with meaningful names: tickets, fare, total and discounted_total. It prints the same Pay 11.5, and now people can read the code and fix it.
  3. Two naming conventions. snake_case, small letters with _ between the words, is what Python's style guide asks for. camelCase, each new word after the first starting with a capital letter, is used in JavaScript and Java. A mix such as total_Price is used nowhere, and Python reads it as a different name from total_price: pick one style and use it every time.
  4. White space is free. The tidy-up's function, f(a,b) with c=a*b, rewritten: meaningful names, spaces around = and *, an indent of 4 spaces, and blank lines after the function. It still works out 17.5: style is for people, not for Python.
  5. Long lines are hard to read: the Python style guide says 79 characters at most, and a long line makes the reader scroll sideways. The tidy-up's long print, with the names from the function before, is 107 characters on one line, so it is broken inside its brackets onto shorter lines. It still prints one line: 17.5 is the cost of 7 tickets at a fare of 2.5 each, which is a lot.

Quick check: names and style

Have a go

Quick check: names and style

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 it: first letter and the rest

Code: python
word = "price"
print(word[0])
print(word[1:])
print(word[0].upper() + word[1:])
print("total_price".split("_"))

# word[0] is the first letter. word[1:] is everything after it.

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

Your turn: change the style

Write three functions about naming styles. to_snake_case(name) changes camelCase into snake_case. to_camel_case(name) changes snake_case into camelCase. is_snake_case(name) is True when the name has only small letters, digits and underscores, is not empty and does not start with a digit. Press Run Tests to check.

Code: python
def to_snake_case(name):
    # Change camelCase into snake_case.
    # "totalPrice" becomes "total_price". "age" stays "age".
    # Hint: a capital letter becomes an underscore and a small letter.
    return None


def to_camel_case(name):
    # Change snake_case into camelCase.
    # "total_price" becomes "totalPrice". "age" stays "age".
    # Hint: use split("_"). word[0] is the first letter. word[1:] is the rest.
    return None


def is_snake_case(name):
    # True if the name is not empty, does not start with a digit, and has only
    # small letters, digits and underscores. "total_price" is True. "totalPrice" is False.
    return None

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.