Course outline · 0% complete

0/27 lessons0%

Course overview →

Naming things well

lesson 3-3 · ~8 min · 10/27

Names are for humans

Python accepts almost any variable name, but code is read by people far more often than it is written. Compare:

x = 12
y = 3
z = x * y
price_per_ticket = 12
ticket_count = 3
total_price = price_per_ticket * ticket_count

Both compute 36. Only one explains itself.

The hard rules, which Python enforces:

  • Names use letters, digits, and underscores only, and cannot start with a digit
  • No spaces (that is why we write ticket_count, the underscore style Python programmers call snake_case)
  • Names are case-sensitive: Score and score are different variables
  • Reserved words like print, if, and while should not be used as names

The soft rule, which professionals enforce: a name should say what the value means, not what type it is or where you got it.

Picking a name for a count of unread emails

The best name is unread_email_count.

snake_case, meaning lowercase words joined by underscores, is the Python convention, and the name says what the value means rather than where it came from.

The alternatives each fail in their own way:

candidateproblem
unread email countspaces are illegal in Python names
UnreadEmailsvalid, but this style is reserved for classes in Python
x2tells a reader nothing at all

UnreadEmails is the interesting failure, because it runs fine. It is the normal style in Java and C#, so it is not wrong in any absolute sense, it is just not what a Python reader expects, and surprising a reader has a real cost.

The same program with honest names

Same values, same output, and now the code explains itself.

width = 8
height = 5
area = width * height
print(area)

Output

40

Reading the pieces

  • Every occurrence of a name changes together, including the ones inside the multiplication and the print. A rename is not a rename until it is complete.
  • Renaming x to width on line 1 but not on line 3 makes Python complain that x is not defined. That error is the good outcome, because a half-finished rename fails loudly instead of computing something wrong.
  • The line area = width * height is now checkable by eye. A reader who knows what a rectangle is can confirm the logic without being told what the program does.

The name of the style itself

The style is called snake_case.

Python programmers use it for variable and function names, and it is named after the way underscores make a name look like it is slithering along the ground.

Other languages prefer camelCase, capitalizing each later word as in totalPrice, which you will meet in the JavaScript courses.

Neither style is better, and the reason to know both is that consistency inside one codebase matters far more than the choice between them. Mixed styles in one file are the actual problem, because a reader starts wondering whether the difference means something.