How to fix NameError: name “nltk” is not defined?

How to fix the nameerror: name nltk is not defined error message in Python?

This error is raised when you are using the Natural Language Toolkit (NLTK) in your Python code.

In this article, we’ll show you how to troubleshoot this error message. So, in order to get the solutions, continue reading.

What is NLTK?

NLTK stands for Natural Language Toolkit, a leading platform for building Python programs to work with human language data.

What is “nameerror name ‘nltk’ is not defined”?

The “nameerror: name ‘nltk’ is not defined” occurs because you either didn’t install the NLTK package using pip.

Or you installed it on a different version of Python.

And also, when you try to use the Natural Language Toolkit (nltk) without importing it first.

In addition to that, it indicates that the Python interpreter is unable to find a reference to the “nltk module in your code.

Why does the “name ‘nltk’ is not defined” nameerror occur?

This error occur because of several reasons, such as:

❌ When you haven’t installed the “nltk” module on your system or it may be outdated.

❌ When you did not import the “nltk” module or if it is not installed correctly.

❌ Incorrect import statement.

❌When there’s an issues with the environment variables, which can cause Python to fail to recognize the ‘nltk’ library.

Different solutions on how to fix “nameerror: name nltk is not defined”?

To fix this nameerror name ‘nltk’ is not defined, you need to install the “nltk” module.

Here are the different ways you can install the “nltk” module.

Solution 1: Install “nltk” module

All you have to do is open your command prompt or terminal.

Also you can head over to the root directory of your project and execute the following command:

If you are using Python 2:

✅ pip install nltk

If you are using Python 3:

✅ pip3 install nltk

or

✅ python3 -m pip install nltk

If you are using Jupyter Notebook:

✅ !pip install nltk

or

✅ !pip3 install nltk

If you are using Anaconda:

✅ conda install -c anaconda nltk 

Use this if you get permissions error:

✅ sudo pip3 install nltk

Use this if you don’t have pip in your PATH environment variable:

✅ python -m pip install nltk

For windows:

✅ py -m pip install nltk

Solution 2: Import “nltk” module

After the “nltk” module is installed successfully, do not forget to import it before using otherwise, you will keep encountering this error message.

You have to import the “nltk” library in your Python script or interactive session using the following command:

import nltk

Solution 3: Check the installed nltk module

If this code displays the version number of the installed “nltk” module.
It means you successfully installed and imported the nltk package.

import nltk
print(nltk.__version__)

Output:

3.8.1

So since we have successfully installed and imported the module, let’s try to use “nltk” in the Python script.

Example code:


import nltk

nltk.download('punkt')

sentence = "Hi welcome to itsourcecode"

tokens = nltk.word_tokenize(sentence)

print(tokens)

Output:

['Hi', 'welcome', 'to', 'itsourcecode']

Conclusion

In conclusion, the error message nameerror: name ‘nltk’ is not defined occurs when you try to use the Natural Language Toolkit (nltk) without importing it first.

To fix this error you need to install the “nltk” module. The solution is simple and easy, yet it is effective.

By following the provided solution above, we can guarantee that you’ll be able to fix this error right away.

We are hoping that this article helps you to resolve the error. Thank you for reading Itsourcecoders!😊

Function-related NameError

NameError on a function usually means the function was not defined yet, the wrong name was used, or the function is in a different scope.

Common triggers

  • Function name typo. caclulate() instead of calculate().
  • Called before def. At module level.
  • Function in wrong module. Imported from a different module than expected.
  • Decorated function shadowed. Decorator returned wrong name.

Diagnostic pattern

# BAD — undefined function
def main():
    result = compute_total()   # NameError if compute_total not defined

main()

# GOOD — check spelling and scope
def compute_total():
    return 42

def main():
    result = compute_total()
    print(result)

main()

# For decorated functions, make sure functools.wraps is used
from functools import wraps

def my_decorator(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
        return fn(*args, **kwargs)
    return wrapper

Best practices

  • Use editor autocomplete. Prevents most typo NameError.
  • Order definitions before calls at module level.
  • Use type hints. Editor flags undefined names immediately.
  • Use functools.wraps in decorators to preserve the original function name.

Frequently Asked Questions

What is Python NameError and what causes it?

NameError is raised when Python encounters a name (variable, function, class) that hasn’t been defined in the current scope. Most common causes: typo in variable name, using a variable before assigning it, missing import, or referencing a variable that was defined inside a function but accessed outside it.

How do I fix ‘name X is not defined’?

Check three things: (1) Is the name a typo? Compare with the spelling where you defined it. (2) Did you import it? Add ‘from module import X’ or ‘import module’ at the top. (3) Is X defined in a different scope (inside a function, conditional branch, or with-block) that hasn’t executed yet at the point you’re using it? Move the definition before the use.

Why does my variable work in one cell but not another (Jupyter)?

Jupyter kernels keep state between cells. If you defined X in cell 5 and run cell 3 later, X exists. But after Kernel-Restart, only the cells you re-run define their variables. Always run cells top-to-bottom on a fresh kernel before submitting. Use ‘Restart and Run All’ to verify your notebook is reproducible.

What is the difference between NameError and AttributeError?

NameError: the name itself doesn’t exist anywhere in scope (typo, missing import, scope issue). AttributeError: the name exists and points to an object, but that object has no such attribute/method (typo on method name, wrong object type). NameError is about the variable; AttributeError is about what’s inside it.

Where can I find more NameError fixes?

Browse the NameError reference hub for 49+ specific fixes (NumPy, pandas, Jupyter, Python 2 to 3 migration). For Python scope rules see the Python Tutorial hub. For attribute-level errors see AttributeError.

Caren Bautista


Technical Writer at PIES IT Solution

Responsible for crafting clear, well-structured, and beginner-friendly content across the platform. Handles the writing, proofreading, and editorial review of tutorials, guides, and documentation to ensure every article is accurate, readable, and easy to follow.

Expertise: Technical Writing · Content Creation · Documentation · Editorial Writing · JavaScript · TypeScript · Python · Python Errors · HTTP Errors · MS Excel
 · View all posts by Caren Bautista →