How to Fix the Name Error in Python
In this article
This guide explains how to fix the NameError in Python, one of the most common errors beginners and even experienced developers run into. A NameError occurs when Python tries to use a variable, function, or module that hasn't been defined yet. You'll learn what causes it, how to read the error message, and step-by-step methods to resolve it quickly.
What You'll Need
- A Python environment (IDLE, VS Code, PyCharm, or just a terminal with Python installed)
- A script or interactive session where the NameError appears
- Basic familiarity with Python syntax (variables, functions, imports)
Step-by-Step
- Read the full error message. Python's NameError looks like:
NameError: name 'foo' is not defined. The part in quotes tells you exactly which name Python couldn't find. Note the line number at the end of the traceback (e.g.,line 3) — that's where the problem is. - Check for typos. Compare the misspelled name in the error with where you think you defined it. Python is case-sensitive, so
myVarandmyvarare different names. Look for extra spaces, swapped letters, or different capitalization. - Verify the variable is defined before use. In Python, you must assign a value to a variable before you can use it. For example,
print(x)beforex = 5will raise a NameError. Move the assignment above the usage, or initialize the variable earlier. - Check the scope. If you define a variable inside a function, it's local to that function. Trying to use it outside the function will cause a NameError. Similarly, a variable defined at the top level (global scope) is accessible inside functions only if you declare it with
global(or use it read-only, which is fine). To fix, either define the variable in the same scope where you use it, or return it from the function. - Ensure the function or module is imported. If you're using a function from another module (like
math.sqrt), you need to import it first. Addimport mathat the top of your script. For a function you defined yourself, make sure the definition appears before the call, or that the definition is in a module you've imported. - Check for missing quotes or parentheses. A common mistake is forgetting to close a string or a function call, which can cause Python to misinterpret the next line. For example,
print("Hello)— the missing closing quote makes Python treat the rest of the line as part of the string, potentially causing a NameError later. Fix the syntax error first. - Look for accidental deletion or overwriting. If you used a variable earlier but then deleted it with
del, or if you reassigned a name to something else (likelist = [1,2]), that can cause a NameError when you try to use the original meaning. Avoid using built-in names as variable names. - Test in isolation. If the error is in a long script, create a minimal example that reproduces the issue. This helps you see the logic clearly. For instance, if you have a loop that uses a variable, make sure that variable is defined before the loop starts.
Common Mistakes
- Using a variable before assignment. This is the most frequent cause. Python reads your code top to bottom; if you reference a name before it's defined, you get a NameError.
- Misspelling a name consistently. You might define
user_namebut later typeusername. Python treats them as different names. - Forgetting to import a module. Calling
sqrt(16)withoutimport mathgivesNameError: name 'sqrt' is not defined. You need to import the module and usemath.sqrt. - Scope confusion. Defining a variable inside a function and trying to use it outside. The variable exists only within that function's local scope.
- Using a variable name that's also a Python keyword. For example, naming a variable
classordefwill cause a SyntaxError, but usingtypeas a variable name can shadow the built-in and cause weird errors later.
Tips
- Use descriptive variable names. This reduces typos and makes it easier to spot where a name is defined.
- Run your code frequently. Don't write a huge script before testing. Run small sections to catch NameErrors early.
- Use an IDE with autocomplete. IDEs like VS Code or PyCharm highlight undefined names and offer suggestions, which prevents many NameErrors.
- Leverage linting tools. Tools like
flake8orpylintcan detect undefined names before you run the code. - Understand the difference between
NameErrorandUnboundLocalError. AnUnboundLocalErroris a subtype of NameError that occurs when you use a local variable before it's assigned within a function. The fix is similar: assign the variable before using it, or declare itglobalif that's your intent.
Troubleshooting
If the above steps don't resolve the issue, try these additional checks:
- Check the indentation. In Python, indentation defines code blocks. If a line is indented more or less than expected, it might be outside the function or loop where the variable is defined, causing a scope issue. Look for inconsistent spaces or tabs.
- Look for circular imports. If you have multiple modules that import each other, a NameError can occur because a module isn't fully loaded when it's referenced. Restructure your imports to avoid circular dependencies.
- Check for name shadowing in loops. If you use a loop variable like
iand then try to useiafter the loop, it should still exist (in Python 3, loop variables are not deleted). But if you delete it inside the loop, it won't exist afterward. - Use a debugger. Set a breakpoint before the error line and inspect which variables are defined. In VS Code, you can hover over a variable to see its value; if it's undefined, it will show an error.
- Search for the error message online. If you're using a library, the specific name might be defined in a different version or under a different name. Check the library's documentation.
Frequently Asked Questions
What does "NameError: name 'x' is not defined" mean?
It means Python doesn't know any variable, function, or module named 'x'. You either haven't defined it, misspelled it, or it's out of scope.
Why do I get a NameError even though I defined the variable?
This usually happens due to scope. Check if the variable is defined inside a function and you're trying to use it outside. Also, ensure you haven't accidentally deleted it with del.
How do I fix a NameError in a function?
Make sure the variable is defined before the function is called, or pass it as a parameter. If you need to modify a global variable, use the global keyword.
Can a NameError be caused by a missing import?
Yes, absolutely. If you use a function from a module without importing it, Python raises a NameError. For example, using randint without from random import randint.
Is there a difference between NameError and UnboundLocalError?
Yes. UnboundLocalError is a subclass of NameError that occurs when a local variable is referenced before it's assigned within a function. The fix is to assign the variable before using it, or use global if needed.
How can I prevent NameError in the future?
Use consistent naming, run your code often, use an IDE with autocomplete, and avoid using built-in names as variables. Also, keep your functions small and pass data via parameters rather than relying on global variables.