What does NameError: name is not defined mean in Python?
Common Causes
The most frequent cause is a simple typo, like writing 'prnt' instead of 'print'. Another common reason is using a variable before it's assigned, such as referencing a local variable in a function before giving it a value. Missing imports also trigger NameError—if you use 'math.sqrt' without 'import math', Python doesn't know what 'math' is.
Scope issues can also cause NameError: a variable defined inside a function isn't accessible outside it, and global variables need to be declared with 'global' if you want to modify them inside a function.
- Misspelling a variable or function name.
- Using a variable before assigning it a value.
- Forgetting to import a module (e.g., 'import math').
- Trying to access a local variable outside its function scope.
- Using a built-in name that was accidentally overwritten.
How to Fix It
Check the spelling of the name in the error message—Python tells you exactly which name is undefined. Ensure the variable is assigned before use. If it's a module, add the import statement at the top of your file. For scope issues, pass variables as arguments or use 'global' (though it's often better to avoid globals).
If the name is defined in another file, make sure you've imported it correctly. For functions, check that you've defined them before calling. Using an IDE with linting can catch these errors early.
Common mistakes
- Assuming the error is on the line reported—sometimes the variable is defined later in the code.
- Confusing NameError with AttributeError, which is about missing attributes on an object.
- Thinking that defining a variable inside an if block makes it available outside—Python scoping doesn't work that way.
