Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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

  • Last Updated : 28 Nov, 2021

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])




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!