Skip to content

NameError: name 'x' is not defined

Error message

                name 'x' is not defined
              

Quick summary

Python doesn't recognize the name you used — it was never assigned, imported, or defined in the current scope.

Why this happens

  • Typo in the variable or function name

  • Forgot to define the variable before using it

  • Forgot to import a module or function before using it

Minimal example

✗ Broken code
print(count)
✓ Fixed code
count = 0
print(count)

count is never assigned before it is used — define it first so Python recognizes the name.

How to diagnose

  • Check the spelling of the name against its definition or import

  • Verify the name is defined before the line that uses it

  • Check if the name is in a different scope (e.g., a local variable used outside its function)

How to fix

  • Fix the typo to match the defined name

  • Define or assign the variable before using it

  • Add the missing import statement at the top of the file

How to prevent

  • Use an IDE with autocomplete to avoid typos

  • Enable a linter (flake8) to catch undefined names

Related Resources

Related Glossary

Related Lessons

Related Practice

← Back to language