Lingua-e
Python

What is a NameError?

← Errors

A NameError is raised in Python when you try to use a variable or function name that has not been defined in the current scope. Python looks up the name in local, enclosing, global, and built-in scopes and cannot find it.

Why it happens

  • Using a variable before assigning a value to it.
  • Typo in the variable or function name.
  • Trying to use a name that is only defined inside a function from outside it.
  • Forgetting to import a module before using its contents.

Examples

Python

Code that triggers the error

def greet():
    print(message)

greet()

Error output

Traceback (most recent call last):
  File "app.py", line 4, in <module>
    greet()
  File "app.py", line 2, in greet
    print(message)
NameError: name 'message' is not defined

How to fix it

Define the variable before using it. Double-check the spelling of every name. If a variable is defined inside a function, pass it as an argument or return it rather than accessing it from the outer scope. Use an IDE or linter to catch undefined names early.

Fixed code

message = "Hello, world!"

def greet():
    print(message)

greet()  # Hello, world!

Related errors

Ready to practice your English at work?

Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.

Try Lingua-e for free