NameError: name 'X' is not defined in Python [Solved]

avatar
Borislav Hadzhiev

Last updated: Feb 1, 2023
6 min

banner

# NameError: name 'X' is not defined in Python

The Python "NameError: name is not defined" occurs when we try to access a variable or a function that is not defined or before it is defined.

To solve the error, make sure you haven't misspelled the variable's name and access it after it has been declared.

nameerror name is not defined

# Make sure you haven't misspelled the variable or function

Here is an example of how the error occurs.

main.py
employee = { 'name': 'Bobby Hadz', 'age': 30, } # โ›”๏ธ NameError: name 'Employee' is not defined. Did you mean: 'employee'? print(Employee) # ๐Ÿ‘ˆ๏ธ misspelled variable's name

The issue is that we have misspelled the variable's name. Note that the names of variables, functions and classes are case-sensitive.

To solve the error in this scenario, we have to spell the variable's name correctly.

main.py
employee = { 'name': 'Bobby Hadz', 'age': 30, } print(employee)

spell variable name correctly

# Common causes of the 'X' is not defined error

The "NameError: name is not defined" error occurs for multiple reasons:

  1. Accessing a variable that doesn't exist.
  2. Accessing a variable, function or class before it is declared.
  3. Misspelling the name of a variable, a function or a class (names are case-sensitive).
  4. Not wrapping a string in quotes, e.g. print(hello).
  5. Not wrapping a key of a dictionary in quotes.
  6. Using built-in modules without importing them first.
  7. Accessing a scoped variable from outside. For example, declaring a variable in a function and trying to access it from outside.

# Accessing a variable or function that doesn't exist

Make sure you aren't accessing a variable that doesn't exist or has not yet been defined.

main.py
# โ›”๏ธ NameError: name 'do_math' is not defined print(do_math(15, 15)) def do_math(a, b): return a + b

The code sample causes the error because we are trying to call a function before it has been declared.

To solve the error, move the line that calls the function or accesses the variable after it has been declared.

main.py
# โœ… 1) declare the function or variable def do_math(a, b): return a + b # โœ… 2) access it after print(do_math(15, 15)) # ๐Ÿ‘‰๏ธ 30

declare variable before accessing it

Note that you also have to instantiate classes or call class methods after the class has been declared.

The same is the case when working with variables.

main.py
# โ›”๏ธ NameError: name 'variable' is not defined. print(variable) variable = 'bobbyhadz.com'

Make sure to move the line that accesses the variable below the line that declares it.

main.py
variable = 'bobbyhadz.com' print(variable) # ๐Ÿ‘‰๏ธ bobbyhadz.com

# Forgetting to wrap a string in single or double quotes

Another cause of the error is forgetting to wrap a string in single or double quotes.

main.py
def greet(name): return 'Hello ' + name # โ›”๏ธ NameError: name 'Alice' is not defined. Did you mean: 'slice'? greet(Alice) # ๐Ÿ‘ˆ๏ธ forgot to wrap string in quotes

The greet function expects to get called with a string but we forgot to wrap the string in quotes, so the name 'X' is not defined error occurred.

This can also happen when passing a string to the print() function without wrapping the string in quotes.

To solve the error, wrap the string in quotes.

main.py
def greet(name): return 'Hello ' + name print(greet('Alice'))

wrap each string in quotes

# Using a built-in module without importing it

The error is also caused if you use a built-in module without importing it.

main.py
# โ›”๏ธ NameError: name 'math' is not defined print(math.floor(15.5))
We use the math module without importing it first, so Python doesn't know what math refers to.

The "NameError: name 'math' is not defined" means that we are trying to access a function or a property on the math module, but we haven't imported the module before accessing the property.

To solve the error, make sure to import any modules you are using.

main.py
import math print(math.floor(15.5)) # ๐Ÿ‘‰๏ธ 15

The import math line is necessary because it loads the math module into your code.

A module is simply a collection of functions and classes.

You have to load the module first before you can access its members.

# Forgetting to wrap the keys of a dictionary in quotes

The error is also caused if you have a dictionary and forget to wrap its keys in quotes.

main.py
employee = { 'name': 'Bobby Hadz', # โ›”๏ธ NameError: name 'age' is not defined age: 30 # ๐Ÿ‘ˆ๏ธ dictionary key not wrapped in quotes }

Unless you have numeric keys in the dictionary, make sure to wrap them in single or double quotes.

main.py
employee = { 'name': 'Bobby Hadz', 'age': 30 }

# Trying to access a scoped variable from outside

The error also occurs if you try to access a scoped variable from outside.

main.py
def get_message(): message = 'bobbyhadz.com' # ๐Ÿ‘ˆ๏ธ variable declared in function return message get_message() # โ›”๏ธ NameError: name 'message' is not defined print(message)

The message variable is declared in the get_message function, so it isn't accessible from the outer scope.

The best way to solve the error is to declare the variable in the outer scope if you have to access it from outside.

main.py
# ๐Ÿ‘‡๏ธ declare the variable in the outer scope message = 'hello world' def get_message(): return message get_message() print(message) # ๐Ÿ‘‰๏ธ "hello world"

An alternative in this scenario would also be to return the value from the function and store it in a variable.

main.py
def get_message(): message = 'bobbyhadz.com' return message result = get_message() print(result) # ๐Ÿ‘‰๏ธ "hello world"

Another alternative would be to mark the variable as global.

main.py
def get_message(): # ๐Ÿ‘‡๏ธ mark message as global global message # ๐Ÿ‘‡๏ธ change its value message = 'hello world' return message get_message() print(message) # ๐Ÿ‘‰๏ธ "hello world"
Note that using the global keyword should generally be avoided as it makes our code harder to read and reason about.

# Trying to access a variable that is declared in a nested function

If you are trying to access a variable that is declared in a nested function from an outer function, you can mark the variable as nonlocal.

main.py
def outer(): def inner(): message = 'bobbyhadz.com' print(message) inner() # โ›”๏ธ NameError: name 'message' is not defined print(message) outer()

The inner function declares a variable named message but we try to access the variable from the outer function and get the "name message is not defined" error.

To get around this, we can mark the message variable as nonlocal.

main.py
def outer(): # ๐Ÿ‘‡๏ธ initialize message variable message = '' def inner(): # ๐Ÿ‘‡๏ธ Mark message as nonlocal nonlocal message message = 'bobbyhadz.com' print(message) inner() print(message) # ๐Ÿ‘‰๏ธ "bobbyhadz.com" outer()

The nonlocal keyword allows us to work with the local variables of enclosing functions.

Note that we had to initialize the message variable in the outer function, but we were able to change its value in the inner function.

Had we not used the nonlocal statement, the call to the print() function would have returned an empty string.

main.py
def outer(): # ๐Ÿ‘‡๏ธ initialize message variable message = '' def inner(): # ๐Ÿ‘‡๏ธ declares message in inner's scope message = 'hello world' print(message) inner() print(message) # ๐Ÿ‘‰๏ธ "" outer()

# Accessing a class before it is defined

The error also occurs when you access a class before it is defined.

main.py
# โ›”๏ธ NameError: name 'Employee' is not defined emp1 = Employee('bobbyhadz', 100) class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def get_name(self): return self.name

To solve the error, move the instantiation line below the class declaration.

main.py
class Employee(): def __init__(self, name, salary): self.name = name self.salary = salary def get_name(self): return self.name emp1 = Employee('bobbyhadz', 100) print(emp1.name) # ๐Ÿ‘‰๏ธ bobbyhadz

If you are working with a class that comes from a third-party library, then you have to import the class before you are able to use it.

# Be mindful of using import statements in a try/except block

The error might also occur when using an import statement in a try/except block.

main.py
try: # ๐Ÿ‘‰๏ธ code here could raise an error import math result = math.floor(15.5) except ImportError: math.floor(18.5) print(math.floor(20.5))

The code sample works, however, if some code before the import statement throws an error, the module won't get imported.

This is an issue because we are accessing the module in the except block and outside the try/except statement.

Instead, move the import statement to the top of the file.

main.py
# โœ… moved import statement to the top of the file import math try: result = math.floor(15.5) except ImportError: math.floor(18.5) print(math.floor(20.5))

# Conclusion

To solve the Python "NameError: name is not defined", make sure:

  1. You aren't accessing a variable that doesn't exist.
  2. You aren't accessing a variable, function or class before it is declared.
  3. You haven't misspelled the name of a variable, a function or a class (names are case-sensitive).
  4. You haven't forgotten to wrap a string in quotes, e.g. print(hello).
  5. You haven't forgotten to wrap a key of a dictionary in quotes.
  6. You aren't using built-in modules without importing them first.
  7. You aren't accessing a scoped variable from outside. For example, declaring a variable in a function and trying to access it from outside.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev