This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 7: Naming variables

How should I name my variables?

face Josiah Wang

Of course, what you are allowed do is different from what you should do.

Just because a variable name is valid does not mean that it is a sensible name.

Use semantically meaningful names

  • x = 25 does not tell you much. ❌
  • xbscaea = 25 does not make sense. ❌
  • age = 25 is self-explanatory (good!) ✔️
  • age_of_monster = 25 gives a bit more detail (good!) ✔️
  • age_of_a_very_large_and_smelly_and_scary_monster = 25 might be a bit too verbose. Try to keep it shorter. ❌

Use readable names

  • Avoid using l, O, or I alone as a single character variable name. You yourself may have found that confusing to read. Is that a 0 or an O? Or is that a 1 or an l or an I?

  • Ending your variable names with an l or 1 might also be confusing. Is that ideal or idea1? Use with caution.

Do not use Python built-in object names

Do not use Python built-in objects (some of these are not keywords) as variable names (e.g. str, int, list).

You can do it, but you will confuse yourself, others, and the Python interpreter, and suffer the consequences later.

>>> x = str("a string")     # another way to create a str
>>> type(x)
<class 'str'>
>>> str = 3
>>> type(str)               # str is an int. Say that again?
<class 'int'>           
>>> y = str("a new string") # the str type is gone!
** An error message **  
>>> str + "what"            # you cannot add an int and a str together
** An error message **  

Use lower case

The official style guide to Python recommends your variable names to be “lowercase, with words separated by underscores as necessary to improve readability… mixedCase is allowed only in contexts where that’s already the prevailing style (e.g. threading.py), to retain backwards compatibility.” So they are essentially happy with something like height or my_beautiful_home, but do not recommend myBeautifulHome.

For this course, we will try to follow this style guide.

I encourage you to name your variables with lowercase_with_underscores. This is especially important if you are working collaboratively with others.

I am discouraging mixedCase, unless you have a solid reason to use it.

Please do not Capitalise your variable names. The reason will become clearer later on in the course. The only time you may capitalise your variable names is when it is convention to do so (for example X to some input data when using the scikitlearn library - you will use this later on in the course).

The most important thing of all is to be consistent. So definitely do not mix different casing in the same code!