NamePython Error

NameError

NameError: name 'x' is not defined

Traceback

terminal
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    print(username)
NameError: name 'x' is not defined

What causes this error

A variable, function, or class name was used that has not been defined in the accessible scope. Typos, missing imports, or referencing names before assignment are the typical triggers.

How to fix it

Check the spelling of the variable name. Ensure the variable is defined before use. Verify that necessary imports are present at the top of the file. Use an IDE with autocompletion to avoid typos.

Code that causes this error

Broken
print(username)

Fixed code

Fixed
username = "alice"
print(username)

About NameError

A NameError is raised when Python encounters a name (variable, function, class, module) that has not been defined in the current scope. This is a runtime error — it occurs when the interpreter tries to look up a name and cannot find it in the local, enclosing, global, or built-in scopes (the LEGB rule). The most common causes are simple typos in variable names, using a variable before assigning it, forgetting to import a module or function, and referencing a variable that was defined inside a different scope (like inside a function or an if block in some edge cases).

Python 3.12 and later versions provide helpful 'Did you mean?' suggestions when a similar name exists in scope. Using an IDE with autocompletion dramatically reduces NameErrors from typos, and linters like pylint or flake8 can catch undefined names before runtime.

Common scenarios

1

Typos in variable or function names that are hard to spot

2

Using a variable before it has been assigned a value

3

Forgetting to import a module or function before using it

4

Variable shadowing issues between local and global scope

Related errors