Menu

Readability

Meaningful Identifiers

A meaningful identifier is a name for a variable, constant or subprogram that describes its purpose or the data it holds. In a ticket-booking program, ticket_price tells you what the value is, while p gives you no clue. The same applies to subprograms: calculate_total() says what it does, but calc() does not.

Meaningful names make a program easier to understand and maintain. When a name explains itself, you need fewer comments, because the code already shows what the value is for. It also helps when you test or debug: you can follow a value through the program without searching back to find out what it means.

Choosing names

Weak nameMeaningful identifierWhy it is better
pticket_pricesays which price is stored
ttickets_soldsays what has been counted
ddiscount_ratesays what the number is used for

Names should be clear and consistent. Use the same name for the same value throughout, and avoid cryptic names unless their meaning is obvious — i is fine for a simple loop counter, but not much else. A good name is as short as it can be while still being clear, not as long as possible; player_score is better than the_score_that_the_player_has_earned.

Renaming an identifier

If you rename an identifier, every reference to it must be updated. Leave one line out and the program may end up using two names for what should be one value, or it may stop with a NameError when it reaches a name that no longer exists. Changing seats_booked to tickets_sold, for example, means editing every line that uses it.

The program below uses meaningful identifiers throughout:

def share_cost(bill_amount, diners):
    return bill_amount / diners

diners = int(input("How many diners? "))
bill_amount = float(input("Total bill: "))
each_pays = share_cost(bill_amount, diners)
print("Each person pays " + str(round(each_pays, 2)))

Output when the user types 4, 28.40:

How many diners? 4
Total bill: 28.40
Each person pays 7.1

Every name in this program earns its place: diners, bill_amount and each_pays say exactly what they hold, and share_cost() says what the subprogram does. You can follow the calculation without a single comment.

Practise this