Menu

Readability

White Space

White space is the spaces and blank lines in a program that separate code and stop it looking cramped. It does not change what the program does, but it changes how quickly a person can scan it.

A blank line between sections, such as after a subprogram or between setting up variables and using them, shows where one job ends and the next begins, so the layout of the program is easier to follow. Spaces around operators, such as the equals sign and the multiplication sign, keep the parts of an expression apart so you can see the structure at a glance. Too much white space works against you: many blank lines inside a short block break the code into fragments, and badly placed spaces can make a line look untidy rather than clear.

In Python, spaces at the start of a line are indentation, which is part of the block structure. They are not optional decoration: change them and the program may run differently or fail. White space between statements and inside expressions is more flexible, but keep it consistent so the reader knows what to expect.

The short program below uses one blank line between the subprogram and the main code, and spaces around each operator.

def total_cost(price, quantity):
    return price * quantity

item_price = 4
item_count = 6
cost = total_cost(item_price, item_count)
print("Cost: " + str(cost))

Output:

Cost: 24

Practise this