Name Error

Naming Variables in Python

In Python, when you want to declare a variable, you give it a name that then corresponds to that variable's value. For instance, when I write:

a = []

I have now created an empty list that is called “a”. Any time I want to use this list, I use the variable name “a”, which represents that empty list.

There are several styles for naming variable in Python, and as long as you choose a convention that makes sense to you, it will work. Though there are very few restrictions on what you can name your variables in Python, the following are a couple of the most common naming conventions:

this_is_my_list = []
Fig. 1: An underscore separated variable name

thisIsMyList = []
Fig. 2: A camelCased variable name

Generally, you'll also want the variable names you choose to be logical, such that you can easily tell what they represent. For instance, if I’m making a list to store names of students in a class, it would make perfect sense to call this list:

students_in_class = []

By contrast, perhaps this name isn't the best choice:

power_rangers = []

Although technically both of these variable names will work just fine, one is significantly more intuitive for organizing and understanding your code.

NameErrors in Python

NameError exceptions in Python are generally raised when you try to access a variable that you have not defined properly. This could happen because the variable truly hasn't been defined yet, or perhaps only be due to a slight typo. For example:

>>> demetrius = "Villain, what hast thou done?"
>>> aaron = "That which thou canst not undo."
>>> chiron = "Thou hast undone our mother."
>>> print demitrius
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'demitrius' is not defined

In this case, because we've misspelled “demetrius”, Python raises a NameError, letting us know that 'demetrius' wasn't defined. Python doesn't know that we've simply misspelled a variable name; as far as it is concerned, the variable wasn't defined and that's final.

PyLearn, on the other hand, is able to perform a few more specific checks in this case and provide us with an improved message:

>>> print demitrius
NameError: The variable 'demitrius' wasn't defined when you tried to access it.
Possible Typo: Perhaps you meant to access 'demetrius' instead of 'demitrius'.

In general, when you encounter a NameError in Python, verify that variable you're trying to access is indeed defined when and where you're trying to access it.

Though PyLearn will perform a number of additional checks for you, it's best to get into the habit of automatically checking for slight misspellings, pluralization issues, etcetera, whenever you encounter a NameError. We've all been programming for years, and still get tripped up by typos like these for much longer than we're willing to admit!