Friday, December 27, 2024
Google search engine
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 Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments