Saturday, September 6, 2025
HomeLanguagesHow to Fix: NameError name ‘np’ is not defined

How to Fix: NameError name ‘np’ is not defined

In this article, we will discuss how to fix NameError np that is not defined in Python.

When we imported the NumPy module without alias and used np in the code, the error comes up.

Example: Code to depict error

Python3




# import numpymodule
import numpy
  
# create numpy array
a = np.array([1, 2, 3, 45])
  
# display
a


Output:

name 'np' is not defined

Here np is an alias of the NumPy module so we can either import the NumPy module with the alias or import NumPy without the alias and use the name directly.

Method 1: By using the alias when importing the numpy

We can use an alias at the time of import to resolve the error.

Syntax:

import numpy as np

Example: Program to import numpy as alias

Python3




# import numpymodule
import numpy as np
  
# create numpy array
a = np.array([1, 2, 3, 45])
  
# display
a


Output:

array([ 1,  2,  3, 45])

Method 2: Using NumPy directly

We can use NumPy module directly to use in a data structure.

Syntax:

import numpy

Example: Using NumPy directly

Python3




# import numpymodule
import numpy
  
# create numpy array
a = numpy.array([1, 2, 3, 45])
  
# display
a


Output:

array([ 1,  2,  3, 45])
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32270 POSTS0 COMMENTS
Milvus
82 POSTS0 COMMENTS
Nango Kala
6639 POSTS0 COMMENTS
Nicole Veronica
11803 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11869 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7029 POSTS0 COMMENTS
Thapelo Manthata
6705 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS