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 we make it easy to read.
Key words
| Word | What it means | Example |
|---|---|---|
| Naming convention | A set of rules for how names are written. | |
| Meaningful name | A name that says what the value is or what the code does. | total_price |
| snake_case | Small (lower-case) letters, with an underscore _ between words. | total_price |
| camelCase | No spaces. Each new word starts with a capital letter. | totalPrice |
| White space | Spaces, blank lines and indents that make code easy to see. | |
| Line length | How many characters are on one line. | |
| Readability | How easy the code is to read and understand. | |
| Variable | A name that holds a value. | |
| Function | A named piece of code that does a job. |
The cells students fill in are left blank in this preview.
Run it: hard to read
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?
Run it: easy to read
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.
Meaningful names
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
| Convention | How it looks | Where it is used |
|---|---|---|
| snake_case | total_price, first_name | Python: the Python style guide asks for it |
| camelCase | totalPrice, firstName | JavaScript and Java, for variables and functions |
| Mixed styles | total_Price, TotalPrice2 | Nowhere: pick one style and use it every time |
The cells students fill in are left blank in this preview.
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
data-callouts.tip.label
Some teams use a longer line, such as 100 characters. The exact number matters less than everybody using the same one.
Tidy it up
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.
Quick check: names and style
Have a go
Quick check: names and style
4 questionsYour answers are marked here and are not kept. A college account keeps every student’s marks.