Readability
Layout is the way the code in a program is arranged on the page. It covers the order of the statements, where line breaks go and how related lines are grouped together. Good layout does not change what the program does, but it makes the program much easier to read and to change later.
A well-laid-out program is split into logical sections, each doing one job. A common order is:
import lines at the topWhy this order? The reader meets the things the program depends on before the code that uses them, so nothing is a surprise when they reach it.
Related statements should sit together, and one blank line should separate groups that do different jobs. That way the reader can see where one job ends and the next begins. Each statement should also go on its own line rather than being crammed onto a shared line, because a stack of statements on one line is slow to scan and easy to misread.
In this short program the setup, the subprogram and the main program each sit in their own section, with a blank line between them:
# Set up the values
pool_length = 25
target = 1000
# Work out how many lengths make a distance
def lengths_for(distance, length):
return distance // length
# Main program
total = lengths_for(target, pool_length)
print("Lengths: " + str(total))Output:
Lengths: 40
Never let tidying up change the logic. Splitting two statements that share a line onto separate lines, or moving a subprogram below the main program, leaves the output exactly the same. But putting the setup after the main program would break it, because the variables would have no value when they are used.
Edexcel GCSE Computer Science · Readability