NameError: A Step By Step Troubleshooting Guide!

In this article, let us learn what causes NameError and see how we can fix that and get our code up and running again!

Troubleshooting any errors will include the following steps

  • Step#1: Understand the error and its causes
  • Step#2: Figure out which of the causes actually led to the error in your particular case
  • Step#3: Apply the Fix, and test your code to confirm.
  • Step#4: Party!

Let us start by understanding the NameError and its causes!

Step#1: Understanding NameError & Its Root Cause

What’s a NameError?

I always believe an example is the best way to understand anything, so let’s begin with that.

Do you spot anything odd in the following program?

print(a)

It produces a NameError as shown below:

Traceback (most recent call last):
  File "/home/main.py", line 1, in <module>
    print(a)
NameError: name 'a' is not defined

The problem with our code is mentioned in the last line of our error message.

Python didn’t know what ‘a’ is since we did not define it and hence a NameError exception is raised.

When our code is running,

  • python reads through our code one word at a time
  • if it sees a word it does not recognize, it gets stuck as it does not know what to do
  • so it stops the code from running with a NameError

Here’s a fix to the above program, we just define the variable ‘a’ before we call it:

a = 5
print(a)

Now, the program runs smoothly!

5

The above example was too simple. Let’s see another example just to get the concept more concrete!

name = "Sherlock Holmes"
occupation = "Detective"
nationality = "British"

print(name)
print(gender)

Here we are trying to print the variable gender which we did not define earlier. Since the Python interpreter does not recognize it, a NameError is raised as shown below!

Traceback (most recent call last):
  File "/home/main.py", line 6, in <module>
    print(gender)
NameError: name 'gender' is not defined

The fix is simple, we make a variable named “gender” and give it a value

name = "Sherlock Holmes"
occupation = "Detective"
nationality = "British"
gender = "Male"

print(gender)

Now our code works with the following output!

Male

If your problem was as simple as this example that you just forgot to define the variable, then lucky you, your problem is already fixed!

If this was not your issue then fear not, we will get to the bottom of your issue too!

Step#2: Finding The Root Cause In Your Code & Fixing That

Here is a pro tip for you, to fix not just NameError but any error in Python. Whenever your program crashes with an Exception, (take a deep breath and) have a look at the huge wall of error text that just got printed on your screen!

There is actually a lot of information contained in the error message, if you wish to learn the tricks then set aside 10mins of your time and read the following article!

Python: Details contained in an Exception

For visual learners out there we have also made an interesting video on that topic!

4 Main Causes of NameError

Coming back to the topic, there are various causes that can lead to NameErrors, the 4 most common causes are

  1. Misspelling the variable name or reserved Keyword
  2. Referencing a variable before its definition
  3. Referencing a variable outside its scope &
  4. Using a module without importing it

I suggest you go through these causes and their fixes one by one until you have managed to fix your NameError bug!

Cause#1: Misspelling the variable name or reserved keyword

Though it is too obvious, it is worth mentioning, as I have literally spent hours chasing bugs which was just really a typo! So double-check that you have spelled stuff correctly in your code as the very first step!

For example, look at how I misspell this variable:

my_var = "Hello World!"

print(myvar) # oops forgot the underscore!

Or this function call:

def addThree(a, b, c):
    return a + b + c

print(add_three(10,20,30)) # snake_case and camelCase confusions!

Both of them would lead to a KeyError as the interpreter does not know what is myvar or add_three, it knows only my_var and addThree as we defined earlier.

Typos and misspells are not only limited to variable and function names, you can also misspell a reserved keyword like this!

prnt("Hello world!")

The result will be the same, a NameError!

Traceback (most recent call last):
  File "/home/main.py", line 1, in <module>
    prnt("Hello world!")
NameError: name 'prnt' is not defined. Did you mean: 'print'?

Nice of Python to even catch our typos!

Fix for Cause#1: Double/Triple Check the spellings

Patiently read through your code and check all your spellings!

The best way to do this is to use an IDE that does all the heavy lifting for you and just focus on the squiggly lines!!

Cause#2: Referencing a variable before its definition

Just like the title says, sometimes we mistakenly use a keyword and then afterwords define what that keyword is.

For example:

print(word)
word = "Hi"

Python is an interpreted language and executes its programs line by line. The same thing happens here, it executes the first line before it even reads the second line, so don’t be surprised if the NameError is raised!

Fix for Cause#2: Make sure your variable is defined first!

In our example, the fix would be to swap the 2 lines of code!

word = "Hi"
print(word)

Cause#3: Referencing a variable outside its scope

We know how scopes in Python can limit the accessibility of a variable or a function to certain parts only (depending on the level of indentation of the code where the variable is declared)

NameError can be raised when you handle the scopes incorrectly.

For example,

outer_var = "I am outer_var"

def my_func():
    inner_var = "I am inner_var"
    
print(outer_var)
print(inner_var)

if we tried to access inner_var outside my_func, it is not recognized by the interpreter and leads to, you guessed it, a NameError!

I am outer_var
Traceback (most recent call last):
  File "/home/main.py", line 7, in <module>
    print(inner_var)
NameError: name 'inner_var' is not defined. Did you mean: 'outer_var'?

This also applies to other inner blocks like

  • if/else,
  • for-loop,
  • while-loop,
  • nested functions,
  • classes,
  • methods
  • with statement
  • try-except blocks, etc

Note that in every scenario, the same logic applies as to why the exception was raised in the first place, the interpreter does not recognize your word at the given level of scope!

Fix for Cause#3: Check your variable’s scope

Verify the scope of your variable or function and if you are lucky now your code should run okay!

If not then read on, there is still hope!

Cause#4: Using a module without importing it

Sometimes we may mistakenly start using a module without even importing it.

For example,

print(math.sqrt(81))

Here I wanted to use the math module but I forgot to import it:

Output

Traceback (most recent call last):
  File "/home/main.py", line 1, in <module>
    print(math.sqrt(81))
NameError: name 'math' is not defined

That happened because the interpreter did not recognize the math keyword.

Fix for Cause#4: Make sure that the necessary modules are imported before usage

In the previous example, the fix would be

import math
print(math.sqrt(81))

and this should make your code run again!

Making simple mistakes like this is part and parcel of programming, but understanding how to fix mistakes will surely make your life easier!

I hope by now the NameError has been fixed and you have tested and confirmed the fix too!

According to our troubleshooting roadmap, there is just one more pending step here, which is to celebrate our win today!!

For the next step in your Python journey I invite you to master some of the most common errors you will run into in your daily life as a Python developer. We have compiled a list of just 7 exceptions that you need to focus on if you wish to gain mastery of Exceptions in Python!

7 Most Common In-Built Exceptions in Python!

If you are a visual learner here is a YouTube video that we made on that same topic!

And with that, I will end this article.

I hope you enjoyed reading this article and found it useful!

Feel free to share it with your friends and colleagues!

If your thirst for knowledge has not been quenched yet, here are some related articles that might spark your interest!

Related Articles

Python: Catch Exception and Print

6 Common Mistakes While Importing Modules & Their Fixes! (Python)

Mutable and Immutable Data Types in python explain using examples

Thanks to Namazi Jamal for his contributions in writing this article!

Photo of author
Editor
Balaji Gunasekaran
Balaji Gunasekaran is a Senior Software Engineer with a Master of Science degree in Mechatronics and a bachelor’s degree in Electrical and Electronics Engineering. He loves to write about tech and has written more than 300 articles. He has also published the book “Cracking the Embedded Software Engineering Interview”. You can follow him on LinkedIn