Last updated: Apr 8, 2024
Reading timeยท6 min
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.
Here is an example of how the error occurs.
employee = { 'name': 'Bobby Hadz', 'age': 30, } # โ๏ธ NameError: name 'Employee' is not defined. Did you mean: 'employee'? print(Employee) # ๐๏ธ Misspelled the 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.
employee = { 'name': 'Bobby Hadz', 'age': 30, } print(employee)
The "NameError: name is not defined" error occurs for multiple reasons:
print(hello)
.Make sure you aren't accessing a variable that doesn't exist or has not yet been defined.
# โ๏ธ 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.
# โ 1) Declare the function or variable def do_math(a, b): return a + b # โ 2) Access it after print(do_math(15, 15)) # ๐๏ธ 30
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.
# โ๏ธ 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.
variable = 'bobbyhadz.com' print(variable) # ๐๏ธ bobbyhadz.com
Another cause of the error is forgetting to wrap a string in single or double quotes.
def greet(name): return 'Hello ' + name # โ๏ธ NameError: name 'Alice' is not defined. Did you mean: 'slice'? greet(Alice) # ๐๏ธ Forgot to wrap the 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.
print()
function without wrapping the string in quotes.To solve the error, wrap the string in quotes.
def greet(name): return 'Hello ' + name print(greet('Alice'))
The error is also caused if you use a built-in module without importing it.
# โ๏ธ NameError: name 'math' is not defined print(math.floor(15.5))
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.
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.
The error is also caused if you have a dictionary and forget to wrap its keys in quotes.
employee = { 'name': 'Bobby Hadz', # โ๏ธ NameError: name 'age' is not defined age: 30 # ๐๏ธ Dictionary key is not wrapped in quotes }
Unless you have numeric keys in the dictionary, make sure to wrap them in single or double quotes.
employee = { 'name': 'Bobby Hadz', 'age': 30 }
The error also occurs if you try to access a scoped variable from outside.
def get_message(): message = 'bobbyhadz.com' # ๐๏ธ Variable declared in the 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.
# ๐๏ธ 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.
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
.
def get_message(): # ๐๏ธ Mark message as global global message # ๐๏ธ change its value message = 'hello world' return message get_message() print(message) # ๐๏ธ "hello world"
global
keyword should generally be avoided as it makes our code harder to read and reason about.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
.
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
.
def outer(): # ๐๏ธ Initialize the 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.
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.
def outer(): # ๐๏ธ Initialize the `message` variable message = '' def inner(): # ๐๏ธ Declares `message` in inner's scope message = 'hello world' print(message) inner() print(message) # ๐๏ธ "" outer()
The error also occurs when you access a class before it is defined.
# โ๏ธ 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.
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.
The error might also occur when using an import statement in a try/except block.
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.
# โ Moved the 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))
To solve the Python "NameError: name is not defined", make sure:
print(hello)
.