NameError name is not defined

suggest change

Is raised when you tried to use a variable, method or function that is not initialized (at least not before). In other words, it is raised when a requested local or global name is not found. It’s possible that you misspelt the name of the object or forgot to import something. Also maybe it’s in another scope. We’ll cover those with separate examples.


It’s simply not defined nowhere in the code

It’s possible that you forgot to initialize it, specially if it is a constant

foo   # This variable is not defined
bar() # This function is not defined

Maybe it’s defined later:

baz()

def baz():
    pass

Or it wasn’t imported:

#needs import math

def sqrt():
    x = float(input("Value: "))
    return math.sqrt(x)

Python scopes and the LEGB Rule:

The so-called LEGB Rule talks about the Python scopes. It’s name is based on the different scopes, ordered by the correspondent priorities:

Local → Enclosed → Global → Built-in.

As an example:

for i in range(4):
    d = i * 2
print(d)

d is accesible because the for loop does not mark a new scope, but if it did, we would have an error and its behavior would be similar to:

def noaccess():
    for i in range(4):
        d = i * 2
noaccess()
print(d)

Python says NameError: name 'd' is not defined

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Common Exceptions:
* NameError name is not defined

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
171 Common Exceptions
185 pyaudio
186 shelve